gpt4 book ai didi

php - 正则表达式或功能

转载 作者:搜寻专家 更新时间:2023-10-31 21:35:54 25 4
gpt4 key购买 nike

我有一个html内容如下:

$html = "My name is Varun-Kumar. My webpage is <a href='http://varundeboss.com/varun-home-page'>Varundeboss</a> Also http://varundeboss.home.com/varun-home-page";

现在我想从 html 中删除所有出现的“-”,除非它出现在 anchor 标记内以及出现在以“http://”、“https://”和“www. "

我可以使用以下代码为 anchor 标记执行此操作:

$result = preg_replace('%-(?![^<]*</a>)%i', '', $html);

谁能帮助我如何更改此正则表达式以包含“http://”、“https://”和“www”的大小写。

感谢您的帮助!

谢谢,瓦伦

最佳答案

你可以使用这个模式:

$result = preg_replace('~(?:https?:\S+|<a\b[^>]*)(*SKIP)(?!)|-~i', ' ', $html);

想法是在尝试匹配 - 之前先匹配您要避免的内容。然后,您使用始终为假的 (?!) 使模式失败,并使用 (*SKIP)

停止回溯

此方法的优点是您可以自由选择替换目标字符串的内容,而无需使用 preg_replace_callback():

$result = preg_replace_callback('~(https?:\S+|<a\b[^>]*)|-~i', 
function ($m) { return ($m[1])? $m[1] : ' ';},
$html);

在这两个示例中,您可以轻松添加您想要的:img 标签、www 等。

关于php - 正则表达式或功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19834671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com