php preg_replace 匹配 [英] php preg_replace matches
本文介绍了php preg_replace 匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何访问 preg_replace 中的匹配项作为可用变量?这是我的示例代码:
How do you access the matches in preg_replace as a usable variable? Here's my sample code:
<?php
$body = <<<EOT
Thank you for registering at <!-- site_name -->
Your username is: <!-- user_name -->
<!-- signature -->
EOT;
$value['site_name'] = "www.thiswebsite.com";
$value['user_name'] = "user_123";
$value['signature'] = <<<EOT
live long and prosper
EOT;
//echo preg_replace("/<!-- (#?\w+) -->/i", "[$1]", $body);
echo preg_replace("/<!-- (#?\w+) -->/i", $value[$1], $body);
?>
我不断收到以下错误消息:
I keep getting the following error message:
解析错误:语法错误,意外'$',期待 T_STRING 或 T_VARIABLE第 18 行
Parse error: syntax error, unexpected '$', expecting T_STRING or T_VARIABLE on line 18
当匹配变量用引号括起来时,上面带有[$i]"的注释行可以正常工作.是不是我遗漏了一些语法?
The above remarked line with "[$i]" works fine when the match variable is enclosed in a quotes. Is there a bit of syntax I'm missing?
推荐答案
像这样:echo preg_replace("/<!-- (#?\w+) -->/", '$1',$body);
顺便说一下,/i
修饰符只会对没有大小写字母的模式造成伤害.
The /i
modifier can only do harm to a pattern with no cased letters in it, incidentally.
这篇关于php preg_replace 匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文