加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 将目标属性添加到html链接

发布时间:2020-12-13 22:05:47 所属栏目:PHP教程 来源:网络整理
导读:我想要找到没有target属性的 HTML字符串中的所有链接,以便可以添加它. 下面是一些检测属性的代码……我可以尝试搜索输出以查找是否有目标但是有一种更简单的方法可以检测它是否具有目标属性? $content = 'pThis is some a href="http://www.google.com"samp
我想要找到没有target属性的 HTML字符串中的所有链接,以便可以添加它.

下面是一些检测属性的代码……我可以尝试搜索输出以查找是否有目标但是有一种更简单的方法可以检测它是否具有目标属性?

$content = '<p>This is some <a href="http://www.google.com">sample text</a> with
<a href="htttp://bing.com" target="_blank" class="test">links</a>.</p>';

preg_match_all('/<a([^>]*)href="([^"]*)"([^>]*)>([^<]*)</a>/',$content,$matches);

print_r($matches);

输出:

Array
(
    [0] => Array
        (
            [0] => <a href="http://www.google.com">sample text</a>
            [1] => <a href="htttp://bing.com" target="_blank" class="test">links</a>
        )

    [1] => Array
        (
            [0] =>  
            [1] =>  
        )

    [2] => Array
        (
            [0] => http://www.google.com
            [1] => htttp://bing.com
        )

    [3] => Array
        (
            [0] => 
            [1] =>  target="_blank" class="test"
        )

    [4] => Array
        (
            [0] => sample text
            [1] => links
        )

)

解决方法

解决这个问题而不是正则表达式的另一种方法是使用php DOM extension,它允许你通过DOM API操作XML文档.
这是一个例子:

$content = '<p>This is some <a href="http://www.google.com">sample text</a> 
with <a href="htttp://bing.com" target="_blank" class="test">links</a>.</p>'; 

$doc = new DOMDocument();
$doc->loadHTML($content);
$links = $doc->getElementsByTagName('a');
foreach ($links as $item) {
    if (!$item->hasAttribute('target'))
        $item->setAttribute('target','_blank');  
}
$content=$doc->saveHTML();
echo $content;

这是更好的,而不是使用难以保持和调试的复杂正则表达式.

希望能帮助到你.祝好运!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读