在 PHP 中的 preg_replace 中使用 $ 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1400768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:24:47  来源:igfitidea点击:

Using $ variables in preg_replace in PHP

phpvariablespreg-replace

提问by Steve

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

嗯...如何在调用 preg_replace 时使用变量?

This didn't work:

这不起作用:

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

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

是的,$num前面有一个加号。是的,我想要“ tag the $num as <$text/>”。

回答by Paul Dixon

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

您的替换模式看起来不错,但由于您在匹配模式中使用了单引号,因此不会将 $num 变量插入其中。相反,尝试

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

另请注意,当从这样的“未知”输入构建模式时,使用preg_quote通常是个好主意。例如

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

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

虽然我猜给出了变量名,但在你的情况下它总是数字。

回答by Gumbo

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

变量只会在用双引号声明的字符串中扩展。所以要么使用双引号:

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

Or use string concatenation:

或者使用字符串连接:

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

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

您还应该查看preg_quote您的变量是否可能包含正则表达式元字符。