Koo*_*bin 5 php regex hyperlink
我的应用程序允许用户在我的网站上写评论.它的工作正常.我也有工具在其中插入他们的网页链接.内容与他们自己的网络链接我感觉很好.
现在我想将rel ="nofollow"添加到他们已经编写的内容的每个链接上.
我想在保存数据的同时使用php添加rel ="nofollow".
那么使用php添加rel ="nofollow"或使用rel ="someother nofollow"更新rel ="someother"的简单方法是什么?
一个很好的例子将是非常有效的
ale*_*lex 18
正则表达式确实不是处理HTML的最佳工具,尤其是当PHP内置了非常好的HTML解析器时.
nofollow如果rel已填充属性,此代码将处理添加.
$dom = new DOMDocument;
$dom->loadHTML($str);
$anchors = $dom->getElementsByTagName('a');
foreach($anchors as $anchor) {
$rel = array();
if ($anchor->hasAttribute('rel') AND ($relAtt = $anchor->getAttribute('rel')) !== '') {
$rel = preg_split('/\s+/', trim($relAtt));
}
if (in_array('nofollow', $rel)) {
continue;
}
$rel[] = 'nofollow';
$anchor->setAttribute('rel', implode(' ', $rel));
}
var_dump($dom->saveHTML());
Run Code Online (Sandbox Code Playgroud)
生成的HTML在$dom->saveHTML().除非它将它包装html,body元素等,所以使用它来提取你输入的HTML ...
$html = '';
foreach($dom->getElementsByTagName('body')->item(0)->childNodes as $element) {
$html .= $dom->saveXML($element, LIBXML_NOEMPTYTAG);
}
echo $html;
Run Code Online (Sandbox Code Playgroud)
如果你有> = PHP 5.3,更换saveXML()用saveHTML()拖放的第二个参数.
这个HTML ...
<a href="">hello</a>
<a href="" rel="">hello</a>
<a href="" rel="hello there">hello</a>
<a href="" rel="nofollow">hello</a>
Run Code Online (Sandbox Code Playgroud)
......被转换成......
<a href="" rel="nofollow">hello</a>
<a href="" rel="nofollow">hello</a>
<a href="" rel="hello there nofollow">hello</a>
<a href="" rel="nofollow">hello</a>
Run Code Online (Sandbox Code Playgroud)