Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preg_replace with array replacements

Tags:

string

regex

php

$string = ":abc and :def have apples.";
$replacements = array('Mary', 'Jane');

should become:

Mary and Jane have apples.

Right now I'm doing it like this:

preg_match_all('/:(\w+)/', $string, $matches);

foreach($matches[0] as $index => $match)
   $string = str_replace($match, $replacements[$index], $string);

Can I do this in a single run, using something like preg_replace?

like image 565
Alex Avatar asked Feb 23 '12 15:02

Alex


3 Answers

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.
like image 51
hakre Avatar answered Oct 17 '22 08:10

hakre


$string = ":abc and :def have apples.";
$replacements = array('Mary', 'Jane');

echo preg_replace("/:\\w+/e", 'array_shift($replacements)', $string);

Output:

Mary and Jane have apples.
like image 29
Qtax Avatar answered Oct 17 '22 07:10

Qtax


Try this

$to_replace = array(':abc', ':def', ':ghi');
$replace_with = array('Marry', 'Jane', 'Bob');

$string = ":abc and :def have apples, but :ghi doesn't";

$string = strtr($string, array_combine($to_replace, $replace_with));
echo $string;

here is result: http://sandbox.onlinephpfunctions.com/code/7a4c5b00f68ec40fdb35ce189d26446e3a2501c2

like image 8
Iatrarchy Avatar answered Oct 17 '22 07:10

Iatrarchy