开发者

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 ?


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 :)


$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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜