PHP if字符串包含<;a>;标签


PHP if string contains an <a> tag

假设我提交了一个带有消息的表单:

Hi! What's up? <a href="http://test.com">Click here</a> to check out <a href="http://test.com">my</a> website.

如何用PHP检测字符串是否包含<a>标记,然后将rel="nofollow"添加到其中?因此它将更改为:

Hi! What's up? <a href="http://test.com" rel="nofollow">Click here</a> to check out <a href="http://test.com" rel="nofollow">my</a> website.

关于代码将如何运行的一点猜测?

$string = $_POST['message'];
if (*string contains <a> tags*) {
    *add rel="nofollow"*
}

始终存在DOMDocument对象。

<?php
$dom = new DOMDocument();
$dom->loadHTML('<a href="http://example.com">woo! examples!</a>');
foreach ($dom->getElementsByTagName('a') as $item) {
  $item->setAttribute('rel', 'nofollow'); 
}
echo $dom->saveHTML();
?>