Using $ variables in preg_replace in PHP

前端 未结 2 824
情歌与酒
情歌与酒 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

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

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

    Or use string concatenation:

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

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

提交回复
热议问题