如何使用preg_replace从PHP字符串中删除链接


How to remove links from a PHP string using preg_replace

我使用的是聊天机器人程序脚本,如果用户名是test@test.com,机器人程序将用mailto链接回复@<a href= mailto:test@test.com>test@test.com</a>。我希望回复只有test@test.com,没有链接,我尝试了preg_replacestr_replace,但我真的不知道要使用的确切代码,我尝试过以下代码,但没有成功!

$name = preg_replace('/<a href="([^<]*)">([^<]*)<'/a>/', '', $name);

我用来替换的整个代码是:

$name = str_replace (chr(0xc2).chr(0xa0), "_", $name);
$name = str_replace ("'", "", $name);
$name = str_replace ("&quot;", '"', $name);
$name = str_replace ("&amp;", "&", $name);
$name = str_replace ("&lt;", "", $name);
$name = str_replace ("&gt;", "", $name);
$name = str_replace ("&", "_", $name);
$name = str_replace ("*", "_", $name);
$name = preg_replace('/[^ 'p{L}'p{N} '@ '_ '- '.'#'$'&'!]/u', '', $name);
$name = preg_replace('/<a href="([^<]*)">([^<]*)<'/a>/', '', $name);

为什么要替换它?只需将preg_match()与类似的regex一起使用即可:

<a href=[^>]+>([^<]*)</a>

所以总的来说,你的代码看起来像这个

<?php
$regex = '#<a href=[^>]+>([^<]*)</a>#';
$email = '<a href= mailto:test@test.com>test@test.com</a>';
preg_match($regex, $email, $matches);
var_dump($matches[1]);
/*
output:
string(13) "test@test.com"
*/
?>

上面的答案在进行preg_replace时做了很多假设,所以很不幸它会失败很多:(以下是为什么…

  • 它假定每个链接都有直接在"a"标记后面的"href"属性。如果前面有一个不同的属性呢
  • 它假定"a"标记中没有其他html标记。如果链接中有"strong"标记,则该链接将不匹配
  • 我也很确定,如果列表中有多个链接,它会删除第一个链接和第二个链接之间的所有内容,因为它没有任何东西可以阻止它贪婪
  • 最后,它并没有被告知要麻木不仁。这意味着,如果链接中有A HREF,也不会找到它

我并不是说我的解决方案是100%安全的,但我已经在我所知道的场景中进行了测试,我认为这是对上述答案的升级!。。。

$email = preg_replace("/<a.+?href.+?>.+?<'/a>/is","",$email);

"i"修饰符使其不敏感's'修饰符考虑了可能被换行符打断的链接。

我总是建议用不同格式、不同顺序的不同链接填充字符串。这总是测试工作的最佳方式。假设每个类型的链接都是我的测试会让你陷入很多棘手的情况:)

祝你好运!