Question

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

In: text .... <a href="mailto:somebody@example.org">not needed</a> text
Out: text .... somebody@example.org 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:hello@somedomain.org">not needed</a><a href="mailto:somebody@example.org"><font size="3">somebody@example.org</font></a>
Out: somebody@example.org">
Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top