Sometimes, you want to replace a word in a string with another word. You may want to replace all swear words with more neutral statements, replace BBCode tags with the corresponding HTML tags or use placeholders for data in a templating system.

In PHP, there are several functions to replace something:

Often, you want to replace a pattern. Consider our templating system in which we have placeholders for data:

Hello {planet}. My name is {name}.
In this case, we want to replace {anything} with some other string, which depends on the string between the curly braces. We may have an array which contains the data to replace the placeholders with.

We can make a regular expression to match our placeholders: /{[^}]*}/ The regex is is between slashes. It matches a curly brace, then anything and then a closing curly brace. The [^}] means "anything but a }", which may repeat zero or more times because of the asterisk.

Now, if we use preg_replace, we can replace all our placeholders. However, with preg_replace we can only replace all tags with the same string. We want to vary the replacement string depending on the source string, but preg_replace allows only a static string.

If we want to replace a regex depending on the content of the match, we have three options:

  • Use preg_replace_callback, where the callback determines the replacement string.
  • First search all patterns using preg_match, then replace all matches with str_replace.
  • Using only str_replace, which does not work in all cases.