tags:

views:

70

answers:

1

I want to replace all "mailto:" links in html with plain emails.

In: text .... <a href="mailto:[email protected]">not needed</a> text
Out: text .... [email protected] text

I did this:

$str = preg_replace("/\<a.+href=\"mailto:(.*)\".+\<\/a\>/", "$1", $str);

But it fails if there are multiple emails in string or html inside "a" tag

In: <a href="mailto:[email protected]">not needed</a><a href="mailto:[email protected]"><font size="3">[email protected]</font></a>
Out: [email protected]">
+3  A: 

Make your match non-greedy by adding ? to quantifiers + and * as:

$str = preg_replace("/\<a.+?href=\"mailto:(.*?)\".+?\<\/a\>/", "$1", $str);

Also you need not escape < and > and since there are some / in the pattern its better to use a different delimiter and since you are not doing any variable interpolation inside the pattern, there is no need to enclose it in " this way you can avoid escaping " inside the pattern:

$str = preg_replace('#<a.+?href="mailto:(.*?)".+?</a>#', "$1", $str);
codaddict
Lauri