14

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/>".

2 Answers 2

15

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.

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

1 Comment

Thanks Gumbo, Paul - both your inputs helped!
15

Variables will only be expanded in strings declared with double quotes. So either use double quotes:

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

Or use string concatenation:

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

You should also take a look at preg_quote if your variables may contain regular expression meta characters.

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.