Say I have a string like this: <? $string = "Hi <<name>>"; $name = "John Smith"; ?> I want to run a preg_replace operation, and replace <<name>> with $name (John Smith). My current code is [php] <? $string = preg_replace("~<<(.*?)>>~i", ${'$1'}, $string) ?> PHP: But that gives me "Undefined variable: $1" notice. Seriously, need help here. Cheers, BP
I would do: <?php $string = "Hi <<name>>"; $name = "John Smith"; $string = str_replace("<<name>>", $name, $string); ?> PHP:
Yes, that would work, but it needs to be preg. For instance, if it was <<test>> it would have to be replaced with $test, and <<sjopjef>> would be replaced with $sjopjef Thanks, Josh
It's work with any variable you create. Like your example above. $string = "Hi <<sjopjef>>"; $sjopjef = "php-lover"; preg_match('/<<(.+)>>/',$string,$match); echo preg_replace('/<<sjopjef>>/',$$match[1],$string); PHP:
Hi and thanks. I got that working, but it only works if I have one variable - ifm I have more it gives me a notice. So I think I'd have to do something with foreeach, and get each result.
Here's an example of how to use that code. $string = array("Hi <<sjopjef>>","Hi <<a>>","Hi <<b>>"); $sjopjef = "php-lover"; $a = "John"; $b = "Paul"; foreach($string as $welcome){ preg_match('/<<(.+)>>/',$welcome,$match); $str = preg_replace('/<<.+>>/',$$match[1],$welcome); echo $str.'<br />'; } PHP:
Sorry to be a pain, I really am. But I can't store my thing as an array. it has to be a string, so it could be something like Hi <<a>> and <<b>> Code (markup): Which is why I was thinking of foreaching the $match variable, but am unsure on exxactly how to do that. Thanks for all your help
The easy way to answer correctly your problem is to post your code, so we can read and fix it easily. cheers
You could try preg_replace_callback() - the callback can check the values and use the names (which will have to be global, unfortunately).
My code is (literally): <?php //This string is actually retrieved from a HTML file $string = "Hi <<fname>> <<lname>> "; $fname = "John"; $lname = "Smith"; ?> PHP: Because the HTML file is editable by users, to use PHP variables, they need to be able to input a HTML equivelant (and that is the WinWord mail merger format ), and that must then convert to the actual variable in the backend. Cheers, BP