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

标签 php regex

我想在 HTML 字符串中找到所有没有 target 属性的链接,以便添加它。

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

$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;

这比使用难以维护和调试的复杂正则表达式更好。

希望对您有所帮助。祝你好运!

关于php - 将目标属性添加到 html 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19124360/

相关文章:

PHP代码未在MYSQL数据库PDO中插入详细信息

php - Moodle enrol_manual_enrol_users 不起作用

python - 检查列表中的两个项目是否相同?

regex - 如何用vim中的单词替换uuid列

java - 在同一字符串中匹配多个正则表达式时未获得所需的结果

python - 仅当后跟数字时,正则表达式才会有条件地替换值

PHP SVN 更新 - TortoiseSVN

php - 出于调试目的,如何将任何对象转换为字符串?

PhpStorm 无法识别类中的 PDO 方法

PHP 使用 preg_replace : "Delimiter must not be alphanumeric or backslash" error