Replacing Text with preg_replace() In PHP

Here, you will learn how to replace the text from a string. In simple words, you can say that you need to replace a portion of a string with new text.

Simple search – and – replace functions like str_replace() are useful for replacing literal strings.

However, if you need to replace more complex patterns of text, you can use PHP’s regular expression string replacement functions, preg_replace() and preg_replace_callback() .

Replacing Text with preg_replace()

The preg_replace() Function is used to match a pattern against a target string, much like preg_match(), and replace the matched text with different text.

In its most basic form, preg_replace() takes three arguments:

  • The regular expression to search for (as a string).
  • The replacement text to replace any matched text with.
  • The target string to search through.

The preg_replace() returns the target string with any matched text replaced by the replacement text.
Here,we will illustrate a simple example that searches for a dollar symbol followed by a number of digits, a dot, and two more digits, and replaces this text with the string “ [CENSORED] “ :

$text = “The wholesale price is $90.20.”;
// Displays “The wholesale price is [WELLDONE].”
echo preg_replace( “/\\$\d+\.\d{2}/”, “[WELLDONE]”, $text );

You can also use backreferences within the replacement string — simply write a dollar ( $ ) symbol followed by the backreference number:

$text = “Author: Steinbeck, John”;
// Displays “Author: John Steinbeck”
echo preg_replace( “/(\w+), (\w+)/”, “$2 $1”, $text );

If you want to include the entire matched text in the replacement string, use $0 (a dollar followed by zero):

$text = “T-shirt: $3.99”;
// Displays “T-shirt: Only $3.99”
echo preg_replace( “/\\$\d+\.\d{2}/”, “Only $0”, $text );

You can also pass an array of target strings for preg_replace() to work on, much like using preg_grep(). If you do this, preg_replace() returns the array of strings with any matched text replaced by the replacement text:

Code

$text = array(
“T-shirt: $3.99”,
“Trouser: $4.99”,
“Jeans: $5.99”
);
$newText = preg_replace( “/\\$\d+\.\d{2}/”, “Only $0”, $text );1
echo “ < pre > ”;
print_r( $newText );
echo “ < /pre > ”;

Output

This code displays:
Array
(
[0] = > T- shirt Only $3.99
[1] = > Trouser: Only $4.99
[2] = > Jeans: Only $5.99
)

You can also pass an array of regular expression strings to the function, and it will match and replace each expression in turn with the replacement string:

Code

$text = “The wholesale price is $89.50. “ .
“The product will be released on Jan 16, 2014.”;
$patterns = array(
“/\\$\d+\.\d{2}/”,
“/\w{3} \d{1,2}, \d{4}/”
);
echo preg_replace( $patterns, “[WELLDONE]”, $text );

Output

The wholesale price is [WELLDONE]. The product will be released on [WELLDONE].

If you also pass an array of replacement strings, the matched text from each expression in the expressions array is replaced by the corresponding string in the replacements array:

Code

$text = “The wholesale price is $89.50. “
. “The product will be released on Jan 16, 2010.”;
$patterns = array(
“/\\$\d+\.\d{2}/”
, “/\w{3} \d{1,2}, \d{4}/”
);
$replacements = array(
“[PRICE FIXED]”,
“[DATE FIXED]”
);
echo preg_replace( $patterns, $replacements, $text );

Output

The wholesale price is [PRICE FIXED]. The product will be released on [DATE FIXED].

If your replacements array contains fewer elements than your expressions array, matched text for any expression without a corresponding replacement is replaced with an empty string.
For example:

Code

$text = “The wholesale price is $89.50. “ .
“The product will be released on Jan 16, 2014.”;
$patterns = array(
“/\\$\d+\.\d{2}/”,
“/\w{3} \d{1,2}, \d{4}/”
);
$replacements = array(
“[PRICE FIXED]”
);
echo preg_replace( $patterns, $replacements, $text );

Output

The wholesale price is [PRICE CENSORED]. The product will be released on.

preg_replace() supports two more optional arguments.

  • The first argument, an integer, lets you restrict how many times the pattern (or patterns) is replaced in the target string (or strings):

    // Displays “71%, 83%”
    echo preg_replace( “/\d+\%(,| )*/”, “”, “14%, 59%, 71%, 83%”, 2 );

This pattern replaces a percentage figure (followed optionally by commas and spaces) with an empty string. Because a limit argument of 2 was supplied, only the first two matches are replaced.The second optional argument is a variable to hold the number of replacements performed. (If you want to use this argument but you don ’ t want to limit the number of replacements, pass – 1 for the previous argument.)

This example replaces the character ‘ % ’ with the string “ percent ” four times, and displays the number of replacements:

preg_replace( “/\%/”, “ percent”, “14%, 59%, 71%, 83%”, -1, $count );
echo $count; // Displays “4”

The number stored in $count is the total number of replacements performed. So if you pass an array of 10 target strings and text is replaced once in five of them, then $count equals 5.

Scroll to Top