As you are replacing all with the same, you could do either pass an array

$content = preg_replace(array($pattern1,$pattern2, $pattern3), '', $content);

or create one expression:

$content = preg_replace('/regexp1|regexp2|regexp3/', '', $content);

If the "expressions" are actually pure character strings, use str_replace instead.

Answer from Felix Kling on Stack Overflow
🌐
PHP
php.net › manual › en › function.preg-replace.php
PHP: preg_replace - Manual
Defaults to -1 (no limit). ... If specified, this variable will be filled with the number of replacements done. preg_replace() returns an array if the subject parameter is an array, or a string otherwise.
🌐
W3Schools
w3schools.com › php › func_regex_preg_replace.asp
PHP preg_replace() Function
The preg_replace() function returns a string or array of strings where all matches of a pattern or list of patterns found in the input are replaced with substrings. There are three different ways to use this function: 1. One pattern and a ...
🌐
SitePoint
sitepoint.com › php
Regular expresson match and replace multiple strings - PHP - SitePoint Forums | Web Development & Design Community
September 24, 2012 - i need to declate a pattern for each string i want to match. if there way i can match right or left and replace according to that ? if you found left replace with right, if you found right replace with left acrording to the order in the pattern $pattern = array('/[^-{]\\bleft\\b/','/[^-{]\\bright\\b/'); $replace = array('right','left'); $subject = 'body {left: 24px;} p {right: 24px;}'; $subject = preg_replace($pattern, $replace, $subject); echo $subject; this code doesn’t work.
Top answer
1 of 2
1

I think you will need to incorporate word boundaries with a regex-based function.

Consider this strtr() demo:

$string="Rah rah, sis boom bah, I read a book on budweiser";
$p1 = array('sis','boom','bah');
$r1 = 'cheers';
$p2 = array('boo','hiss');
$r2 = 'jeers' ;
$p3 = array('guinness','heineken','budweiser');
$r3 = 'beers';

$replacements=array_merge(
    array_combine($p1,array_fill(0,sizeof(r1)),
    array_combine($p2,array_fill(0,sizeof(r2)),
    array_combine($p3,array_fill(0,sizeof(r3))
);
echo strtr($string,$replacements);

Output:

Rah rah, cheers cheers cheers, I read a jeersk on beers
//                                      ^^^^^ Oops

You will just need to implode your needle elements using pipes and wrap them in a non-capturing group so that the word boundaries apply to all substrings, like this:

Code: (Demo)

$string="Rah rah, sis boom bah, I read a book on budweiser";
$p1 = ['sis','boom','bah'];
$r1 = 'cheers';
$p2 = ['boo','hiss'];
$r2 = 'jeers' ;
$p3 = ['guinness','heineken','budweiser'];
$r3 = 'beers';
$find=['/\b(?:'.implode('|',p2).')\b/','/\b(?:'.implode('|',swap=[r2,$r3];
var_export($find);
echo "\n";
var_export($swap);
echo "\n";
echo preg_replace($find,$swap,$string);

Output:

array (
  0 => '/\\b(?:sis|boom|bah)\\b/',                 // unescaped: /\b(?:sis|boom|bah)\b/
  1 => '/\\b(?:boo|hiss)\\b/',                     // unescaped: /\b(?:boo|hiss)\b/
  2 => '/\\b(?:guinness|heineken|budweiser)\\b/',  // unescaped: /\b(?:guinness|heineken|budweiser)\b/
)
array (
  0 => 'cheers',
  1 => 'jeers',
  2 => 'beers',
)
Rah rah, cheers cheers cheers, I read a book on beers

*Notes:

The word boundaries \b ensure that whole words are match, avoiding unintended mismatches.

If you need case-insensitivity, just use the i flag at the end of each regex pattern. e.g. /\b(?:sis|boom|bah)\b/i

2 of 2
0
$subject = 'sis + boo + guinness';
echo preg_replace(['/sis|boom|bah/','/boo|hiss/','/guinness|heineken|budweiser/'],['cheers','jeers','beers'],$subject);
// the result would be cheers + jeers + beers

replacement The string or an array with strings to replace. If this parameter is a string and the pattern parameter is an array, all patterns will be replaced by that string. If both pattern and replacement parameters are arrays, each pattern will be replaced by the replacement counterpart. If there are fewer elements in the replacement array than in the pattern array, any extra patterns will be replaced by an empty string. ...

If subject is an array, then the search and replace is performed on every entry of subject, and the return value is an array as well.

🌐
PHP Freaks
forums.phpfreaks.com › php coding › regex help
Multiple Patterns for preg_replace - Regex Help - PHP Freaks
November 28, 2009 - I'm trying to replace words in paragraphs with random words from a database (a-la madlib), but I don't want it to grab partial words. For example, I want it to replace "white" and not part of "whiten" or "whitest". I'm thinking the way to do this is to define individual words as the word preceded...
Top answer
1 of 2
5

Use a callback, you can detect which pattern matched by using capturing groups, like (?:(patternt1)|(pattern2)|(etc), only the matching patterns capturing group(s) will be defined.

The only problem with that is that your current capturing groups would be shifted. To fix (read workaround) that you could use named groups. (A branch reset (?|(foo)|(bar)) would work (if supported in your version), but then you'd have to detect which pattern has matched using some other way.)

Example

function replace_callback($matches){
    if(isset($matches["m1"])){
        return "foo";
    }
    if(isset($matches["m2"])){
        return "bar";
    }
    if(isset($matches["m3"])){
        return "baz";
    }
    return "something is wrong ;)";
}

$re = "/(?|(?:regex1)(?<m1>)|(?:reg(\\s*)ex|2)(?<m2>)|(?:(back refs) work as intended \\1)(?<m3>))/";

$rep_string = preg_replace_callback($re, "replace_callback", $string);

Not tested (don't have PHP here), but something like this could work.

2 of 2
1

It seems to me that preg_replace_callback is the most direct solution. You just specify the alternate patterns with the | operators and inside the callback you code an if or switch. Seems the right way to me. Why did you discard it?

An alternative solution is to make a temporary replace to a special string. Say:

// first pass
$subject = preg_replace($pat0, 'XXX_MYPATTERN0_ZZZ', $subject);
$subject = preg_replace($pat1, 'XXX_MYPATTERN1_ZZZ', $subject);
$subject = preg_replace($pat2, 'XXX_MYPATTERN2_ZZZ', $subject);
// second pass
$subject = preg_replace("XXX_MYPATTERN0_ZZZ",$rep0 , $subject);
$subject = preg_replace("XXX_MYPATTERN1_ZZZ",$rep1 , $subject);
$subject = preg_replace("XXX_MYPATTERN2_ZZZ",$rep2 , $subject);

This is very ugly, does not adapt well to dynamic replacements, and it's not foolproof, but for some "run once" script it might be acceptable.

Find elsewhere
🌐
BrainBell
brainbell.com › php › using-preg-replace-callback-array.html
Search & Replace with Multiple Patterns and Callbacks in PHP – BrainBell
August 1, 2022 - This function works the same as the preg_repalce() except that it takes the $callback function instead of the $replacement string. The callback function will be called and passed an array of matched elements in the subject string.
🌐
GitHub
gist.github.com › plasticbrain › 3702974
PHP: (REGEX/preg_replace) replace multiple characters (ie: spaces) · GitHub
September 11, 2012 - PHP: (REGEX/preg_replace) replace multiple characters (ie: spaces) Raw · php-regex-patterns · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
BrainBell
brainbell.com › php › search-and-replace-with-preg_replace.html
Search and replace with preg_replace() in PHP – BrainBell
August 1, 2022 - The preg_replace() function also accepts arrays as both the $pattern and $replacment parameters for multiple pattern matching and replacements. If the replacement is a string and the pattern is an array, all the matched patterns will be replaced ...
🌐
Liferea
lzone.de › examples › PHP preg_replace
LZone
LZone - Cheat Sheets for Sysadmin / DevOps / System Architecture
🌐
PHP Tutorial
phptutorial.net › home › php tutorial › php preg_replace
PHP preg_replace() Function - PHP Tutorial
April 7, 2025 - If the $replacement array has fewer elements than the $pattern array, the preg_replace() function wil replace extra patterns with an empty string. If the $subject is an array, the preg_replace() function searches and replaces each string in the array and returns the result as an array.
🌐
Stack Overflow
stackoverflow.com › questions › 15840564 › how-do-you-replace-multiple-instances-of-a-preg-match-matches-with-different-rep › 15840691
php - How do you replace multiple instances of a preg_match matches with different replacement text? - Stack Overflow
April 5, 2013 - if (preg_match_all ("/\[include=(.+?)\]/", $text, $matches)) { foreach ($matches[0] as $match) { $file = preg_replace("/\[include=/", "", $match); $file = preg_replace("/\]/", "", $file); $file_contents = file_get_contents($file); $text = str_replace("$match", "$file_contents", $text); } } ... preg_match() will match just one occurrence, in your case you should use preg_match_all() (see documentation http://php.net/manual/en/function.preg-match-all.php)
🌐
Zend
php-legacy-docs.zend.com › manual › php5 › en › function.preg-replace
Perform a regular expression search and replace
<?php $string = 'The quick brown fox jumps over the lazy dog.'; $patterns = array(); $patterns[0] = '/quick/'; $patterns[1] = '/brown/'; $patterns[2] = '/fox/'; $replacements = array(); $replacements[2] = 'bear'; $replacements[1] = 'black'; $replacements[0] = 'slow'; echo preg_replace($patterns, $replacements, $string); ?>
🌐
Hacking with PHP
hackingwithphp.com › 4 › 8 › 5 › regular-expression-replacements
Regular expression replacements: preg_replace() – Hacking with PHP - Practical PHP
<?php $a = "Foo moo boo tool foo"; $b = preg_replace("/[A-Za-z]oo\b/e", 'strtoupper("$0")', $a); print $b; ?> This time PHP will replace each match with strtoupper("word "), and, because we have appended an "e" (for execute) to the end of our regular expression, PHP will execute the replacements it makes.