【发布时间】:2013-10-01 19:32:51
【问题描述】:
我想在 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
)
)
【问题讨论】:
-
preg_replace_callback可能是你的朋友:php.net/manual/en/function.preg-replace-callback.php首先匹配完整的锚标签<a .... >然后在回调中搜索目标属性。而且鲍尔默先生不会对htttp://bing.com很满意。哦,等等……