PHP if string contains an <a> tag

681 views Asked by At

Let's say I submit a form with the message:

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

How can detect if the string contains <a> tags with PHP, and then add rel="nofollow" to it? So it would change to:

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.

A little speculation of how the code would function?

$string = $_POST['message'];

if (*string contains <a> tags*) {
    *add rel="nofollow"*
}
1

There are 1 answers

0
boxmein On

There's always the DOMDocument object.

<?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();
?>