preg_用电子邮件地址替换所有maito:标签


preg_replace all maito: tags with the email address

类似于这个问题:

preg_match提取锚上的mailto

,但我试图做一个全局字符串替换在php将转换:

. . href = " mailto: jeff@mycom.com"> Mailme<…(包括"a"标签)

改为"jeff@mycom.com",不带标签。这需要一个替换,而不是一个提取。

我一直在使用preg_replace,但像许多其他人一样,我在regex方面相当差。这是我真正追求的正则表达式,但只要最终解决方案是明确的,最佳实践是受欢迎的。

谢谢!

<?php 
$html = '<a href="mailto:jeff@mycom.com">Mailme</a> (including the "a" tags)';
$html = preg_replace("~<a .*?href=[''|'"]mailto:(.*?)[''|'"].*?>.*?</a>~", "$1", $html);
echo $html;
演示工作

下面的正则表达式将为您工作。

 preg_replace(/<a .*?href=((?:''|'"))mailto:(.*?)$1[^>]*>[^<]+</a>/i, "$2", $html);

在开始和结束标记之间使用[^<]+,因为在html中可能会发生换行,所以.*在那里会失败,[^<]+在极少数情况下(小于号)<出现在标签内容中。>