如何在 preg_replace() 的替换参数中引用完整的字符串匹配?
好的,我有这个 PHP 脚本:
<?php
$stringz = "Dan likes to eat pears and his favorite color is green!";
$patterns = array("/pears/","/green/");
$string = preg_replace($patterns, '<b>\\1</b>', $stringz);
echo "<textarea rows='30' cols='100'>$string</textarea>";
?>
当我运行它时,我得到这个: Dan 喜欢吃 他最喜欢的颜色是 !
应该有一个单词......但它没有......
OK so I have this PHP script:
<?php
$stringz = "Dan likes to eat pears and his favorite color is green!";
$patterns = array("/pears/","/green/");
$string = preg_replace($patterns, '<b>\\1</b>', $stringz);
echo "<textarea rows='30' cols='100'>$string</textarea>";
?>
and when I run it I get this:Dan likes to eat <b></b> and his favorite color is <b></b>!
The is suppose to have a word in it... but it doesn't...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
那是因为您没有明确捕获任何内容。当然,
\\0
捕获整个匹配,但是为了捕获特定部分,如果要使用\\1
,则需要使用捕获组,\\2
、\\3
等。将$patterns
更改为:()
表示捕获组,它们内部捕获的任何值都存储在引用\\n
中,其中\\n
指的是第 1 个索引的n
捕获组。That's because you aren't explicitly capturing anything.
\\0
captures the entire match, of course, but in order to capture specific parts, you need to use capturing groups if you want to use\\1
,\\2
,\\3
, etc. Change$patterns
to this:()
's denote capturing groups, and whatever value is captured inside of them is stored in the reference\\n
, where\\n
refers the the 1-indexedn
th capturing group.将
\\1
更改为\\0
。Change
\\1
for\\0
.怎么样
?
\\1
适用于主题,即括号中的任何内容。How about
?
\\1
applies to a subject, which is whatever you have in parentheses.