Preg_Replace with Array Replacements

Using preg_replace on an array

preg_replace doesn't modify in place. To permanently modify $array, you simply need to assign the result of preg_replace to it:

$array = preg_replace("/\d{1,2}IPT\.\w/", "IPT", $array);

works for me.

$array = array('00IPT.A', '0IPT.A');
$array = preg_replace("/\d{1,2}IPT\.\w/", "IPT", $array);
var_dump($array);
// output: array(2) { [0]=> string(3) "IPT" [1]=> string(3) "IPT" }

Note: the \d{1,2} means one or two digits.

If you want to do this to a two-dimensional array, you need to loop through the first dimension:

$array = array( array('00IPT.A', 'notmatch'), array('neither', '0IPT.A') );    
foreach ($array as &$row) {
$row = preg_replace("/\d{1,2}IPT\.\w/", "IPT", $row);
}
var_dump($array);

output:

array(2) { 
[0]=> array(2) {
[0]=> string(3) "IPT"
[1]=> string(8) "notmatch"
}
[1]=> &array(2) {
[0]=> string(7) "neither"
[1]=> string(3) "IPT"
}
}

Note that you have to loop through each row by reference (&$row) otherwise the original array will not be modified.

Preg_replace with array replacements

You could use preg_replace_callback with a callback that consumes your replacements one after the other:

$string = ":abc and :def have apples.";
$replacements = array('Mary', 'Jane');
echo preg_replace_callback('/:\w+/', function($matches) use (&$replacements) {
return array_shift($replacements);
}, $string);

Output:

Mary and Jane have apples.

Php preg_replace with array in elements

You can use preg_replace_callback_array

It uses array of patterns->replacement functions almost identical to yours.

I've made a little example for you:

<?php

// initial array
$emoticons = [
':)' => '<img src="assets/smiles/smilesblank.png" alt="smile" class="img-responsive" />',
':-)' => '<img src="assets/smiles/smilesblank.png" alt="smile" class="icon_smile" />',
':D' => '<img src="assets/smiles/smilesblank.png" alt="smile" class="icon_laugh" />',
':d' => '<img src="assets/smiles/smilesblank.png" alt="laugh" class="icon_laugh" />',
';)' => '<img src="assets/smiles/smilesblank.png" alt="wink" class="icon_wink" />',
':P' => '<img src="assets/smiles/smilesblank.png" alt="tounge" class="icon_tounge" />',
':-P' => '<img src="assets/smiles/smilesblank.png" alt="tounge" class="icon_tounge" />',
':-p' => '<img src="assets/smiles/smilesblank.png" alt="tounge" class="icon_tounge" />',
':p' => '<img src="assets/smiles/smilesblank.png" alt="tounge" class="icon_tounge" />',
':(' => '<img src="assets/smiles/smilesblank.png" alt="sad face" class="icon_sad" />',
':o' => '<img src="assets/smiles/smilesblank.png" alt="shock" class="icon_shock" />',
':O' => '<img src="assets/smiles/smilesblank.png" alt="shock" class="icon_shock" />',
':0' => '<img src="assets/smiles/smilesblank.png" alt="shock" class="icon_shack" />',
':|' => '<img src="assets/smiles/smilesblank.png" alt="straight face" class="icon_straight" />',
':-|' => '<img src="assets/smiles/smilesblank.png" alt="straight face" class="icon_straight" />',
':/' => '<img src="assets/smiles/smilesblank.png" alt="straight face" class="icon_straight" />',
':-/' => '<img src="assets/smiles/smilesblank.png" alt="straight face" class="icon_straight" />'
];

// prepare callbacks
$callbacks = [];
foreach ($emoticons as $smileCode => $replacement) {
// regular expression, nothing smart, just plain replacement
$regex = '~' . preg_quote($smileCode, '~') . '~';
$callbacks[ $regex ] = function () use ($replacement) {
return $replacement;
};
}

$text = "Hello :), this is cool :P smile and :-| another one";

echo "<pre>\n";
echo preg_replace_callback_array($callbacks, $text);

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 string with array in preg_replace

You can use it like this:

$str = "Hello world. It's a beautiful day.";
$para = array("/world/","/day/");
$newstr = preg_replace($para,'',$str);
echo $newstr;

preg_replace to preg_replace_callback with an array as replacement

You need to use the use keyword to pull in $array into your anonymous function...

return preg_replace_callback ( '#\{([a-z0-9\-_]*?)\}#Ssi' , function ($matches) use ($array) {
return ( ( isset ( $array[$matches[1]] ) ) ? $array[$matches[1]] : '' );
} , $template );

Replacing array variables in string with preg_replace

You need to use preg_replace_callback for this:

$val = preg_replace_callback('/\$params\[(\d+)\]/', function ($m) use ($params)
{ return $params[$m[1]]; }, $query);
//=> type=butter&color=yellow&taste=good&content=low-fat

preg_replace: how to consider whole array of patterns before replacing?

I don't think there is any option like that. However, you could use an associative array to store your replacements and sort it using uasort and strlen, so larger matches would come first and you wouldn't need to manage your array order manually.

Then you can use array_keys and array_values to act just like your separated $old and $new arrays.

$replacements = array(
'†' => '/â€/',
'’' => '/’/',
);

// sorts the replacements array by value string length keeping the indexes intact
uasort($replacements, function($a, $b) {
return strlen($b) - strlen($a);
});

$str = 'The programmer’s becoming very frustrated';
$result = preg_replace(array_values($replacements), array_keys($replacements), $str);

EDIT: As @CasimiretHippolyte pointed out, using array_values is not necessary on the first parameter of the preg_replace function in this case. It would only return a copy from $replacements with numerical indexes but the order would be the same. Unless you need an array with identical structure to $old from your question, you do not need to use it.

Preg replace with words from an array

You can use indexed arrays with preg_replace().

<?php
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns = array();
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements = array();
$replacements[0] = 'slow';
$replacements[1] = 'black';
$replacements[2] = 'bear';
echo preg_replace($patterns, $replacements, $string);
?>

The above example will output:

The slow black bear jumped over the lazy dog.

PHP: preg_replace with arrays will not replace whitespace with hyphen

$string = preg_replace(array('/\s/', '/\W/'), array('-', ''), $string);

On the first step, spaces are replaced with - and on the second step both the replaced hyphen and ! are stripped off (replaced with empty string) because - is also a non-word character. Note that the output of first replacement was feded as input to the second replacement.

$string = preg_replace(array('/\s/', '/\W/'), array('_', ''), $string);

Produces new_page because at first spaces are replaced with _ and on the second replacement all the non-word characters must be replaced with an empty string. Since _ is not a non-word character, it won't get removed. ! is a non-word character , so it got removed.

You could do like this to get your desired output.

$string = 'new page!';
echo preg_replace(array('/\s/', '/[^-\w]/'), array('-', ''), $string);

Output:

new-page

OR

change the order.

$string = 'new page!';
echo preg_replace(array('/[^\s\w]/', '/\s/'), array('', '-'), $string);

Output:

new-page


Related Topics



Leave a reply



Submit