原话
$string = '<a href="/home/top">here is some text</a>. <a href="/links/abc">some links here</a>...';
//more links and other html. more link like <a href="/home/below">, <a href="/links/def">...
我需要改变
<a href="/links/abc"> => <a href="#" onclick="link('abc|123')">
<a href="/links/def"> => <a href="#" onclick="link('def|123')">
<a href="/links/ghi"> => <a href="#" onclick="link('ghi|123')">
我尝试使用str_replace
,但很容易将<a href="
替换为<a href="#" onclick="link('
,很难判断下一部分。但如何处理这些取代呢?感谢。
答案 0 :(得分:2)
模式:$pattern = '@<a href=\"/links/([a-zA-Z0-9]*)\">@is';
替换:$replace = '<a href="#" onclick="link(\'\1|123\')">';
致电:$result = preg_replace($pattern, $replace, $string);
答案 1 :(得分:1)
您可以使用preg_replace():
$string = preg_replace('%href="/links/(.+?)"%', 'href="#" onclick="link(\'$1|123\')"', $string);