我想在 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/