我有一个这样的字符串:
(link)there is link1(/link), (link)there is link2(/link)
现在我想设置它看起来像这样的链接:
<a href='there is link1'>there is link1</a>, <a href='there is link2'>there is link2</a>
我尝试使用preg_replace但结果是错误(Unknown modifier 'l'
)
preg_replace("/\(link\).*?\(/link\)/U", "<a href='$1'>$1</a>", $return);
答案 0 :(得分:4)
你实际上距离正确的结果并不远:
/
之前逃离link
(否则,它将被视为正则表达式分隔符并完全破坏您的正则表达式).*?
周围添加一个捕获组(以便稍后可以使用$1
参考)U
因为它会使.*?
贪婪以下是my suggestion:
\(link\)(.*?)\(\/link\)
$re = '/\(link\)(.*?)\(\/link\)/';
$str = "(link)there is link1(/link), (link)there is link2(/link)";
$subst = "<a href='$1'>$1</a>";
$result = preg_replace($re, $subst, $str);
echo $result;
要同时urlencode()
href
参数,您可以使用preg_replace_callback
函数并操纵其中的$m[1]
(捕获组值):
$result = preg_replace_callback($re, function ($m) {
return "<a href=" . urlencode($m[1]) . "'>" . $m[1] . "</a>";
}, $str);