开发者

Replaceing <a href="mailto: with just email aadress

开发者 https://www.devze.com 2022-12-24 16:30 出处:网络
I want to replace all \"mailto:\" links in html with plain emails. In: text .... <a href=\"mailto:somebody@example.org\">not needed</a> text

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><开发者_Go百科;/a>
Out: somebody@example.org">


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消