[英]preg_replace matching but not replacing
在下面的代码中,我试图获取一些文本并围绕它包装一个html achor:
$d = "hello, there, how, are, you";
$d = preg_replace("/[a-zA-Z]+/", "<a href='?word=$1'>$1</a>", $d);
它正确识别每个单词并用替换文本替换每个单词但是它不会将匹配的单词放入字符串中,只是将其留空。 我在使用PHP5。 我错过了什么?
提前致谢。
你忘了抓住比赛了:
$d = "hello, there, how, are, you";
$d = preg_replace("/([a-zA-Z]+)/", "<a href='?word=$1'>$1</a>", $d);
// ^ ^ you forgot these ;-)
$d = preg_replace("/([a-zA-Z]+)/", "<a href='?word=$1'>$1</a>", $d);
针头上没有第一个子图案。 这些都可以。 请注意第一个中的括号,它会保存捕获组。 在第二个我们说$ 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);
您错过了括号:
$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
你忘了添加paranthesis
$d = "hello, there, how, are, you";
$d = preg_replace("/([a-zA-Z]+)/", "<a href='?word=$1'>$1</a>", $d);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.