PHP Regular Expressions – Remove Comments From SQL Text

This short block of PHP code takes a SQL script and removes the “dash-dash” and “/**/” comments from it.  Of course, many languages, including PHP itself, use the “/**/” comment style so this could apply to PHP scripts, as well.

The line that removes the dash-dash style comments could easily be changed to the “//” (slash-slash) style.

Notice the use of percent-signs as delimiters to eliminate the need of escaping forward-slashes.

[code]

// Remove the / * * / style comments
$subject = preg_replace(‘%(/\*)(.*?)(\*/)%s’,””,$subject);

// Remove the — style comments
$subject = preg_replace(‘%(–).*%’,””,$subject);

[/code]

This site uses Akismet to reduce spam. Learn how your comment data is processed.