Home > Web Development > Copying Formatted SQL Code to PHP Using Regular Expressions

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.

  1. I start by pasting in some formatted SQL code.
    Pasted SQL Code
  2. Next I add an empty string named $q, for query.
    Empty Query String
  3. I highlight the SQL code and select Replace from the Search menu.
    1. Make sure to select the Regular Expressions checkbox.
    2. Limit the scope to Selected Text.
    3. Use the Text to Find and Replace With expressions above.

    Highlight, Search, and Replace

  4. 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.
    Finished Result

Nate Smith Web Development

  1. No comments yet.
  1. No trackbacks yet.