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
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
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 );
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.