Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using $ variables in preg_replace in PHP

Ummm... how do I use variables in a call to preg_replace?

This didn't work:

foreach($numarray as $num => $text)
    {
        $patterns[] = '/<ces>(.*?)\+$num(.*?)<\/ces>/';
        $replacements[] = '<ces>$1<$text/>$2</ces>';
    }

Yes, the $num is preceeded by a plus sign. Yes, I want to "tag the $num as <$text/>".

like image 345
Steve Avatar asked Sep 09 '09 16:09

Steve


1 Answers

Your replacement pattern looks ok, but as you've used single quotes in the matching pattern, your $num variable won't be inserted into it. Instead, try

$patterns[] = '/<ces>(.*?)\+'.$num.'(.*?)<\/ces>/';
$replacements[] = '<ces>$1<'.$text.'/>$2</ces>';

Also note that when building up a pattern from "unknown" inputs like this, it's usually a good idea to use preg_quote. e.g.

$patterns[] = '/<ces>(.*?)\+'.preg_quote($num).'(.*?)<\/ces>/';

Though I guess given the variable name it's always numeric in your case.

like image 160
Paul Dixon Avatar answered Sep 17 '22 18:09

Paul Dixon