Copying Formatted SQL Code to PHP Using Regular Expressions
July 19th, 2010
I often find myself copying formatted SQL code into PHP. I like to keep the code semi-formatted while concatenating it into a single string. To make this easy on myself, I use a handy little regular expression search-and-replace in PHPEd. This should work in any text editor that supports regular expressions.
Text to Find:
^([\t ]+)(.+,?)([\t ]*)$
Replace With:
\1$q .= "\2 ";
Look at the screenshots below to see what I mean.
- I start by pasting in some formatted SQL code.
- Next I add an empty string named $q, for query.
- I highlight the SQL code and select Replace from the Search menu.
- Make sure to select the Regular Expressions checkbox.
- Limit the scope to Selected Text.
- Use the Text to Find and Replace With expressions above.
- The finished result is still semi-formatted, and is easy-to-read in PHP. This style of formatting also makes the code easy to work with in PHP. Imagine how easy it would be to add if-then blocks, etc.