Reputation: 2700
The original words
$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">...
I need change to
<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')">
I tried to use str_replace
, but it just easy to replace <a href="
to <a href="#" onclick="link('
and hard to judge the next part. but how to deal with these replace? Thanks.
Upvotes: 1
Views: 118
Reputation: 15837
You can use preg_replace():
$string = preg_replace('%href="/links/(.+?)"%', 'href="#" onclick="link(\'$1|123\')"', $string);
Upvotes: 1
Reputation: 3055
pattern: $pattern = '@<a href=\"/links/([a-zA-Z0-9]*)\">@is';
replace: $replace = '<a href="#" onclick="link(\'\1|123\')">';
call: $result = preg_replace($pattern, $replace, $string);
Upvotes: 2