views:

17

answers:

2

why this code does not work ?

$mx['foo'] = "vvv";
$string = "foo is foobar, baz is widgets";
echo preg_replace("/(foo)/ei",  "$mx[('\\1')]",  $string );

the output must like this

vvv is vvvbar, baz is widgets

+2  A: 

Because you are using double quotes in preg_replace, PHP tries to use your$mx value directly, which produces then error...

Simply escape the $mx, and then it will work:

echo preg_replace("/(foo)/ei",  "\$mx[('\\1')]",  $string );

Or you can do the same by using single quotes:

echo preg_replace("/(foo)/ei",  '$mx[(\'\\1\')]',  $string );
Laimoncijus
or simply ` '$mx["$1"]' `
stereofrog
Wouldn't his output be `"$mx[('foo')] is $mx[('foo')]bar, baz is widgets"` then?
elusive
A: 

Your preg_replace uses double quotes, which are interpreted by PHP. It does not look like you need such a complex setup, since this is a simple string replacement, as far as i can see. A simpler solution would be:

$string = str_replace('foo', 'vvv', $string);

You could use your array, too:

$replacements = array(
    'foo' => 'vvv'
);
foreach ($replacements as $key => $replacement) {
    $string = str_replace($key, $replacement, $string);
}

This would replace all keys in the given array with the associated values.

elusive
You can pass arrays of keys/replacements to `str_replace`, then you don't need to use `foreach` loop
Laimoncijus
But that would imply two arrays, right? This is not very handy here, since keeping them synced is an extra thing to remember.
elusive
@elusive: you can still have single associative replacements array as in your example, just get keys/values accordingly: `preg_replace(array_keys($replacements), array_values($replacements), $string)`
Laimoncijus
You are right! I did not think of that.
elusive