0

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

0

2 Answers 2

3

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 );
Sign up to request clarification or add additional context in comments.

1 Comment

Wouldn't his output be "$mx[('foo')] is $mx[('foo')]bar, baz is widgets" then?
0

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.

3 Comments

You can pass arrays of keys/replacements to str_replace, then you don't need to use foreach loop
But that would imply two arrays, right? This is not very handy here, since keeping them synced is an extra thing to remember.
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)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.