16
$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?

Alex
  • 66,732
  • 177
  • 439
  • 641

4 Answers4

19

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.
hakre
  • 193,403
  • 52
  • 435
  • 836
9
$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.
Qtax
  • 33,241
  • 9
  • 83
  • 121
8

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

Iatrarchy
  • 349
  • 3
  • 12
3

For a Multiple and Full array replacement by Associative Key you can use this to match your regex pattern:

   $words=array("_saudation_"=>"Hello", "_animal_"=>"cat", "_animal_sound_"=>"MEooow");
   $source=" _saudation_! My Animal is a _animal_ and it says _animal_sound_ ... _animal_sound_ ,  _no_match_";


  function translate_arrays($source,$words){
    return (preg_replace_callback("/\b_(\w*)_\b/u", function($match) use ($words) {    if(isset($words[$match[0]])){ return ($words[$match[0]]); }else{ return($match[0]); } },  $source));
  }


    echo translate_arrays($source,$words);
    //returns:  Hello! My Animal is a cat and it says MEooow ... MEooow ,  _no_match_

*Notice, thats although "_no_match_" lacks translation, it will match during regex, but preserve its key. And keys can repeat many times.

Miguel
  • 3,349
  • 2
  • 32
  • 28
  • I recommend to add "u" modifier to the regex for supporting UTF-8 strings: `/\b_(\w*)_\b/u`. BTW, code above has a syntax error, and extra parenthesis at the end. – nikoskip Jan 06 '15 at 18:08
  • Looks like no extra parenthesis issue, i verified the code and is running ok. BUt i added The UTf-8. Thank you – Miguel Jan 09 '15 at 16:00