1
$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 ?

1
  • 2
    whaaaaaaat -2 ?? fuuuuuuuuuuu Commented Jul 5, 2011 at 23:40

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

can you post a example of how would I pass the array? do I replace the function() with it?
2
$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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.