What Delimiter to use for preg_replace in PHP (replace working outside of PHP but not inside)

preg_replace() requires a delimiter character:

preg_replace("/$pat/" ...

Traditionally it’s the forward slash, but it can be any character – especially when you need the forward slash in the regex itself you can resort to another character.

This flexibility allows you to express "/http:\/\/foo\/bar\//" (“leaning toothpick syndrome”) as "!http://foo/bar/!".

The delimiter character is necessary to separate the regex from the regex flags (a.k.a. “modifiers”), for example:

preg_replace("/$pat/i" ...

…this uses the i flag to declare a case-insensitive regex.

Leave a Comment