如何在preg_replace()的替换参数中引用完整的字符串匹配?

问题描述 投票:0回答:3

好的,我有这个 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 likes to eat <b></b> and his favorite color is <b></b>!

应该有一个词在里面...但它没有...

php preg-replace
3个回答
4
投票

那是因为您没有明确捕获任何内容。当然,

\\0
捕获整个比赛,但是为了捕获特定部分,如果您想使用
\\1
\\2
\\3
等,则需要使用捕获组。将
$patterns
更改为此:

 $patterns = array("/(pears)/","/(green)/");

()
表示捕获组,其中捕获的任何值都存储在引用
\\n
中,其中
\\n
指的是 1 索引的第
n
捕获组。


3
投票

\\1
更改为
\\0


0
投票

怎么样

$patterns = array("/(pears)/","/(green)/");

\\1
适用于主题,即括号中的任何内容。

© www.soinside.com 2019 - 2024. All rights reserved.