$re = '/(?<=AS \()([^\(\)]*(\([^\(\)]*\))?[^\(\)]*)*(?=\))/m';
$str = 'WITH Sales_Cust_Join_CTE
AS ( SELECT fs.OrderDateKey,fs.ProductKey,fs.OrderQuantity ,fs.UnitPrice AS TotalSale ,dc.FirstName,dc.LastName FROM [dbo].[FactInternetSales] fs INNER JOIN [dbo].[DimCustomer] dc ON dc.CustomerKey = fs.CustomerKey ) ,Date_CTE
AS ( SELECT DateKey ,CalendarYear FROM [dbo].[DimDate] )
SELECT CalendarYear ,ProductKey ,SUM(TotalSale) AS TotalSales
FROM Sales_Cust_Join_CTE
INNER JOIN Date_CTE ON Date_CTE.DateKey = Sales_Cust_Join_CTE.OrderDateKey
GROUP BY CalendarYear ,ProductKey
ORDER BY CalendarYear ASC ,TotalSales DESC
';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php