我要全部替换“的mailto:”与普通的电子邮件中的HTML链接。

In: text .... <a href="mailto:somebody@example.org">not needed</a> text
Out: text .... somebody@example.org text

我这样做:

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

但是,如果在字符串多个电子邮件或HTML内侧“一”的标签

失败
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">
有帮助吗?

解决方案

请您的匹配的非贪婪按加入?到量词+*为:

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

你也不必逃避<>和因为在模式有一些/它能够更好地使用不同的分隔符,因为你没有做图案内的任何变量插值,也没有必要把它们放在"这这样就可以避免逸出图案内"

$str = preg_replace('#<a.+?href="mailto:(.*?)".+?</a>#', "$1", $str);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top