I need to detect whether a string contains HTML tags.
if(!preg_match(\'(?<=<)\\w+(?=[^<]*?>)\', $string)){
return $string;
}
I would recommend you to allow defined tags only! You don't want the user to type the <script>
tag, which could cause a XSS vulnerability.
Try it with:
$string = '<strong>hello</strong>';
$pattern = "/<(p|span|b|strong|i|u) ?.*>(.*)<\/(p|span|b|strong|i|u)>/"; // Allowed tags are: <p>, <span>, <b>, <strong>, <i> and <u>
preg_match($pattern, $string, $matches);
if (!empty($matches)) {
echo 'Good, you have used a HTML tag.';
}
else {
echo 'You didn\'t use a HTML tag or it is not allowed.';
}
If your not good at regular expressions (like me) I find lots of regex libraries out there that usually help me accomplish my task.
Here is a little tutorial that will explain what your trying to do in php.
Here is one of those libraries I was referring to.