Using $ variables in preg_replace in PHP

前端 未结 2 827
情歌与酒
情歌与酒 2021-02-07 19:36

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

This didn\'t work:

foreach($numarray as $num => $text)
    {
        $patterns[] = \'/

        
2条回答
  •  春和景丽
    2021-02-07 20:01

    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[] = '/(.*?)\+'.$num.'(.*?)<\/ces>/';
    $replacements[] = '$1<'.$text.'/>$2';
    

    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[] = '/(.*?)\+'.preg_quote($num).'(.*?)<\/ces>/';
    

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

提交回复
热议问题