preg_replace匹配但不替换

时间:2012-01-27 14:54:28

标签: php regex

在下面的代码中,我试图获取一些文本并围绕它包装一个html achor:

$d = "hello, there, how, are, you";
$d = preg_replace("/[a-zA-Z]+/", "<a href='?word=$1'>$1</a>", $d);

它正确识别每个单词并用替换文本替换每个单词但是它不会将匹配的单词放入字符串中,只是将其留空。我在使用PHP5。我错过了什么?

提前致谢。

5 个答案:

答案 0 :(得分:6)

你忘记了比赛:

$d = "hello, there, how, are, you";
$d = preg_replace("/([a-zA-Z]+)/", "<a href='?word=$1'>$1</a>", $d);
//                  ^         ^ you forgot these ;-)

答案 1 :(得分:4)

$d = preg_replace("/([a-zA-Z]+)/", "<a href='?word=$1'>$1</a>", $d);

答案 2 :(得分:4)

您的针头中没有第一个子图案。这些都可以。请注意第一个中的括号,它会保存捕获组。在第二个我们说$ 0,这意味着整场比赛。

preg_replace("/([a-zA-Z]+)/", "<a href='?word=$1'>$1</a>", $d);
preg_replace("/[a-zA-Z]+/", "<a href='?word=$0'>$0</a>", $d);

答案 3 :(得分:1)

您错过了括号:

$d = "hello, there, how, are, you";
$d = preg_replace("/([a-zA-Z]+)/", "<a href='?word=$1'>$1</a>", $d);

有一个免费的工具,有助于学习正则表达式(大多数口味,包括JS)。下载并享受http://www.radsoftware.com.au

答案 4 :(得分:0)

您忘记添加括号

$d = "hello, there, how, are, you";
$d = preg_replace("/([a-zA-Z]+)/", "<a href='?word=$1'>$1</a>", $d);