문제

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">
도움이 되었습니까?

해결책

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top