rklockner Posted July 11, 2014 Share Posted July 11, 2014 I'm trying to search a string for all occurences of a pattern, then append text after that pattern. The example is: SUM("foo") as "bar" and have it display as: SUM("foo") over() as "bar" The "SUM" could be any SQL aggregate and be case insensitive. So For bonus points, let's say the valid aggregates are array('SUM', 'MAX', 'MIN', 'AVG'). My plan right now is to figure it out for SUM, then loop it replacing the aggregate. This is what I have so far... and it is not working. $l= 'SUM("foo") as "bar"'; $l=preg_replace('/([^"]+")/','\0 over()',$l); Thanks, Ryan Quote Link to comment Share on other sites More sharing options...
rklockner Posted July 11, 2014 Author Share Posted July 11, 2014 I should also note that "foo" may, or may not, have quotes around it. Quote Link to comment Share on other sites More sharing options...
Psycho Posted July 11, 2014 Share Posted July 11, 2014 (edited) Are "foo" and "bar" always going to be "foo" and "bar" or can they be variable text values? EDIT: Also, you say the value inside the aggregate function may or may not have quotes. Can it use single quotes as well? And what about the quotes around "Bar" can that use single or double quotes - or no quotes? Edited July 11, 2014 by Psycho Quote Link to comment Share on other sites More sharing options...
Psycho Posted July 11, 2014 Share Posted July 11, 2014 (edited) I made some assumptions and made this so it would be very flexible $functions = array('SUM', 'MAX', 'MIN', 'AVG'); $patterns = array(); $replacemetns = array(); foreach($functions as $func) { $patterns[] = "#({$func})\(([^\)]*)\) as (\"){0,1}([^\"]*)(\"){0,1}#"; $replacements[] = "\\1(\\2) over() \\3\\4\\5"; } $output = preg_replace($patterns, $replacements, $input); If this is your input SELECT field1, field2, field3, SUM('field3') as 'field3sum', --Single quotes MAX("field4") as "field4max", --Double quote AVG(field5) as field5avg --No quotes FROM table_name This will be the output SELECT field1, field2, field3, SUM('field3') over() 'field3sum', --Single quotes MAX("field4") over() "field4max", --Double quote AVG(field5) over() field5avg --No quotes FROM table_name Edited July 11, 2014 by Psycho Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.