foo
foo

Reputation: 41

replace strings with variables

$var1 = 'abc';
$var2 = '123';

How can I replace %var1 and %var2% from a string like this:

aaaaaaaa%var1%bbbbbbbbb%var2%ffffffff

with the value of $var1 and $var2 ?

Upvotes: 1

Views: 150

Answers (3)

alex
alex

Reputation: 490273

Assuming >= PHP 5.3...

preg_replace_callback('%(\w+?)%', function($matches) use ($var1, $var2) {
   return $$matches[1][0];
}, $str);

As you can see, you need to pass a reference to each of the outer variables to the closure.

You are probably better constructing an array with the replacement variables, and just passing that array in and then subscripting it...

preg_replace_callback('%(\w+?)%', function($matches) use ($vars) {
   return isset($vars[$matches[1][0]]) ? $vars[$matches[1][0]] : $matches[0][0];
}, $str);

I haven't got a chance to test this code right now, but I believe the general principle is sound :)

Upvotes: 2

webbiedave
webbiedave

Reputation: 48897

$var1 = 'abc';
$var2 = '123';
$subject = 'aaaaaaaa%var1%bbbbbbbbb%var2%ffffffff';

echo str_replace(array('%var1%', '%var2%'), array($var1, $var2), $subject);

// output: aaaaaaaaabcbbbbbbbbb123ffffffff

http://us.php.net/manual/en/function.str-replace.php

Upvotes: 2

user554546
user554546

Reputation:

If I'm reading your question correctly, you want to take the string literal

'aaaaaaaa%var1%bbbbbbbbb%var2%ffffffff' and replace the substrings var1 and var2 with 'abc' and '123', respectively, right? In that case, preg_replace should do the trick.

Upvotes: 1

Related Questions