Multiple Replace (Probably Preg_Replace) of Same String with Array

Multiple replace (probably preg_replace) of same string with array

why not use

$retString = vsprintf('banana is %s, apple is %s, tomato is %s', $myArray);  
return $retString;

preg_replace arrays with multiple patterns per replacement

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($p1),$r1)),
array_combine($p2,array_fill(0,sizeof($p2),$r2)),
array_combine($p3,array_fill(0,sizeof($p3),$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('|',$p1).')\b/','/\b(?:'.implode('|',$p2).')\b/','/\b(?:'.implode('|',$p3).')\b/'];
$swap=[$r1,$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

Replace same character several times with different string

If you have control over what the replacement character is, use sprintf

sprintf('Hello %s, how %s %s?', 'World', 'are', 'you');

or vsprintf:

vsprintf('Hello %s, how %s %s?', array('World', 'are', 'you'));

And even if you don't:

$str = 'Hello ?, I hope ? ?.';
$str = str_replace('?', '%s', $str);
$str = sprintf($str, "World", "you're", "fine");

PHP preg_replace three times with three different patterns? right or wrong?

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.

trying to replace an array of strings with a new array

preg_replace_callback is your friend:

$str = "##Random String## ..... ##Random String##";
$replacement = array ("first replacement", "second replacement");
$i = 0;
$res = preg_replace_callback(
'/##[^#]+##/',
function($m) use(&$i, $replacement) {
return $replacement[$i++];
},
$str);
echo $res;

Output:

first replacement ..... second replacement

replace the same characters with different strings

If * is your only format character, try converting * to %s (also escape existing % to %%), and then using vsprintf(), which takes an array of values to pass in as format parameters:

$str = str_replace(array('%', '*'), array('%%', '%s'), $str);
$newstr = vsprintf($str, $arr);
echo $newstr;

Output:

abc123efg456hij789

Note that if you have more array elements than asterisks, the extra elements at the end simply won't appear in the string. If you have more asterisks than array elements, vsprintf() will emit a too-few-arguments warning and return false.

How to refactor a function to use preg_replace_callback() with multiple regex strings and replacement strings in multiple arrays?

Create an associative array where the keys contain regex patterns and the values contain the callbacks (no prepending/appending strings to the callbacks).

I am not going to rewrite that behemoth from my phone, so I'll demonstrate a single replacement.

Feed your array of patterns and callbacks to preg_replace_callback_array().

Code: (Demo)

$patternCallbacks = [
'~\[code](.*?)\[/code]~is' =>
function($m) {
return '[code]' . base64_encode($m[1]) . '[/code]';
},
// add more elements as needed...
];

echo preg_replace_callback_array(
$patternCallbacks,
'This is my [code]script[/code] to display'
);

Output:

This is my [code]c2NyaXB0[/code] to display

Edit, since you cannot use preg_replace_callback_array(), you will need to make iterated calls of preg_replace_callback().

Code: (Demo)

$patternCallbacks = [
'~\[code](.*?)\[/code]~is' =>
function($m) {
return '[code]' . base64_encode($m[1]) . '[/code]';
},
'~\[php(?:=\d+)?]\K(.*?)\[/php]~is' =>
function($m) {
return base64_encode($m[1]) . '[/php]';
},
];

$text = <<<TEXT
This is my [code]script[/code] to display.
It has [php]unnumbered tag
code[/php] and [php=8]numbered tag code[/php].'
TEXT;

foreach ($patternCallbacks as $pattern => $callback) {
$text = preg_replace_callback($pattern, $callback, $text);
}
echo $text;

Output:

This is my [code]c2NyaXB0[/code] to display.
It has [php]dW5udW1iZXJlZCB0YWcKIGNvZGU=[/php] and [php=8]bnVtYmVyZWQgdGFnIGNvZGU=[/php].

replacing multiple items in a string with str_replace

You can use strtr to do multiple replaces simultaneously:

strtr($test, array('_' => ' ', ',' => ', '));

Using preg_replace to back reference array key and replace with a value

You need to use the /e eval flag, or if you can spare a few lines preg_replace_callback.

  $string = preg_replace(
'|http://mysite.com/script.php\?fruit=([a-zA-Z0-9_-]*)|e',
' "http://mysite.com/" . $fruitArray["$1"] ',
$string
);

Notice how the whole URL concatenation expression is enclosed in single quotes. It will be interpreted as PHP expression later, the spaces will vanish and the static URL string will be concatenated with whatever is in the fruitArray.



Related Topics



Leave a reply



Submit