为链接标签添加目标,只要 href 属性不包含特定单词即可
我创建了这个函数:
<?php
function target_links( $html )
{
$pattern = "/<(a)([^>]+)>/i";
$replacement = "<\\1 target=\"_blank\"\\2>";
$new_str = preg_replace($pattern,$replacement,str_replace('target="_blank"','',$html));
return $new_str;
}
?>
目标是向所有链接标记添加 target="_blank"。
现在我的问题是我需要跳过 href
属性包含特定单词的所有链接标记,但我似乎找不到正确的组合。你们能帮我吗?
I created this function:
<?php
function target_links( $html )
{
$pattern = "/<(a)([^>]+)>/i";
$replacement = "<\\1 target=\"_blank\"\\2>";
$new_str = preg_replace($pattern,$replacement,str_replace('target="_blank"','',$html));
return $new_str;
}
?>
The goal is to add a target="_blank" to all the link tags.
Now my problem is that I need to skip all link tags where the href
attribute contains a specific word, but I can't seem to find the proper combination. Can you guys help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定“不会因为 HTML 损坏而失败”,但如果您可以让 DomDocument 接受您的 html,请尝试以下操作:
I'm not to sure about the "not failing because of broken HTML", but if you can get DomDocument to accept your html, try something like:
正则表达式解决方案可以如下所示:
使用负向前查找
(?!.*?href="[^"]*SPECIFICWORD)
用于检查“SPECIFICWORD”是否在 href 属性内,如果是的,正则表达式不匹配。请参阅此处在线 Regexr
A regex solution can look like this:
A negative lookahead
(?!.*?href="[^"]*SPECIFICWORD)
is used to check if the "SPECIFICWORD" is within the href attribute, if yes the regex does not match.See here online on Regexr