我正在尝试用链接替换所有11位数字。
现在preg_match_all没有返回所有匹配字符串,只返回最后一个匹配的字符串。 preg_replace只返回带有链接的单个11位数字。
//string with numbers to be replaced by links.
$test ="test these numbers 20150423011 20150423012 sdf sdfsdf sdfs fsdf sdfs dfsdfsd 20150423014 fsdf";
$s = preg_match_all("/^((?:.*?)(20\d{9})(?:.*?))+$/",$test,$matches);
foreach($matches[2] as $m){
$replacements[] = "<a href=''>".$m."</a>";
$patterns[] = "/^((?:.*?)(20\d{9})(?:.*?))+$/";
}
$final = preg_replace($patterns, $replacements,$test);
echo $final; //right now gives out the last matched number as a link
答案 0 :(得分:1)
我不完全确定我是否理解了您的问题,但我认为您希望使用<a href...
将您的号码打包为20。
对于这种情况,您可以使用此正则表达式:
(20\d{9})
<强> Working demo 强>
您可以使用此代码:
$re = "/(20\\d{9})/";
$str = "test these numbers 20150423011 20150423012 sdf sdfsdf sdfs fsdf sdfs dfsdfsd 20150423014 fsdf";
$subst = "<a href=''>$1</a>";
$result = preg_replace($re, $subst, $str);
您的结果字符串将是:
test these numbers <a href=''>20150423011</a> <a href=''>20150423012</a> sdf sdfsdf sdfs fsdf sdfs dfsdfsd <a href=''>20150423014</a> fsdf