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 Link to comment https://forums.phpfreaks.com/topic/289751-preg_replace/ 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. Link to comment https://forums.phpfreaks.com/topic/289751-preg_replace/#findComment-1484715 Share on other sites More sharing options...
Psycho Posted July 11, 2014 Share Posted July 11, 2014 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? Link to comment https://forums.phpfreaks.com/topic/289751-preg_replace/#findComment-1484717 Share on other sites More sharing options...
Psycho Posted July 11, 2014 Share Posted July 11, 2014 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 Link to comment https://forums.phpfreaks.com/topic/289751-preg_replace/#findComment-1484720 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.