Reputation: 3823
i write preg match rules:
$subject = 'text <a href="http://google.com">LINK</a> text text <a href="http://google2.com">LINK2</a>';
$search = array(
'/\<a href\="(.*)\">(.*)\<\/a\>/i'
);
$replace = array(
"[a href=\"$1\"]$2[/a]"
);
echo preg_replace($search, $replace, $subject);
When in text only one link everything works great, then more then one - crach code
This i get when is more than one link: "text [a href="http://google.com">LINK text text "
Upvotes: 1
Views: 674
Reputation: 2046
Here's a better regex - it deals with extra fields in the tags:
\<a (?:.*?)href\=[\"\']([^\"\']+?)[\"\'][^\>]*?\>(.+?)\<\/a\>
I think I've escaped all of the special characters in there, I'm not sure what PHP considers 'special', but basically this should match all of the following:
$subject = 'text <a id="test" href="http://google.com">LINK</a> text text <a href="http://google2.com" id="test">LINK2</a> text <a href="http://google3.com">LINK3</a>';
Also, I don't know about PHP, but to match more than one link in Perl, you need the /g modifier on the end of that regex, so:
$search = array(
'/\<a (?:.*?)href\=[\"\']([^\"\']+?)[\"\'][^\>]*?\>(.+?)\<\/a\>/ig'
);
would be your search. Maybe preg_replace does this already, but I'd be surprised, since there are times when you'd only want to replace one instance in your target text.
Upvotes: 0
Reputation: 57729
Change to '/\<a href\="(.*?)\">(.*?)\<\/a\>/i'
to make the matching not-greedy.
Upvotes: 2