Development

Useful regex expressions for PHP preg_replace

Chances are, if you have worked with PHP (or any coding language) for very long, you have run into regular expressions, aka “regex”. Regular Expressions are patterns that are used to match content within other content. A regex, for example, can be used to extract all of the URL links in a text document, or to remove multiple spaces, tabs and line returns. There are many many uses, but we won’t go into that here.

Below are a few handy Regular Expressions that can be used for different purposes that you can stick away in your coding notes for future reference. These are using the preg_replace() function, but you can easily pull out the regex and use it elsewhere:

Remove comments from text

Comments staring with # or //:

$text = preg_replace("%(#|(//)).*%", "", $text);

Comments formatted like /* */:

$text = preg_replace("%/\*(?:(?!\*/).)*\*/%s", "", $text);

Replace tabs with a space

$text = preg_replace("/\t/", " ", $text);

Replace repeating spaces with a single space:

$text = preg_replace("/\s+/", " ", $text);

If you are trying to apply any of these against a html page or code, you’ll find that it may remove valid spaces, tabs and newline characters from within your