在 PHP 中的 preg_replace 中使用 $ 变量
嗯...如何在 preg_replace 调用中使用变量?
这不起作用:
foreach($numarray as $num => $text)
{
$patterns[] = '/<ces>(.*?)\+$num(.*?)<\/ces>/';
$replacements[] = '<ces>$1<$text/>$2</ces>';
}
是的,$num
前面有一个加号。是的,我想“将 $num 标记为 <$text/>
”。
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/>
".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的替换模式看起来不错,但由于您在匹配模式中使用了单引号,因此您的 $num 变量不会被插入其中。相反,请尝试
另请注意,当从像这样的“未知”输入构建模式时,通常最好使用 preg_quote。例如,
虽然我猜想给定变量名称,但在您的情况下它始终是数字。
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
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.
Though I guess given the variable name it's always numeric in your case.
变量只会在 字符串中展开用双引号声明。因此,要么使用双引号:
要么使用字符串连接:
您还应该看看
preg_quote
< /a> 如果您的变量可能包含正则表达式元字符。Variables will only be expanded in strings declared with double quotes. So either use double quotes:
Or use string concatenation:
You should also take a look at
preg_quote
if your variables may contain regular expression meta characters.