[英]Replace content between two tags with preg_replace (php)
我有一个像这样的字符串:
(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);
您实际上离正确的结果不远:
/
之前的link
(否则,它将被视为正则表达式定界符并完全破坏您的正则表达式) .*?
周围添加一个捕获组.*?
(以便您以后可以使用$1
引用) U
因为它会产生.*?
贪婪 这是我的建议 :
\(link\)(.*?)\(\/link\)
和PHP代码 :
$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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.