Detect HTML tags in a string

前端 未结 8 1460
渐次进展
渐次进展 2020-12-04 12:59

I need to detect whether a string contains HTML tags.

if(!preg_match(\'(?<=<)\\w+(?=[^<]*?>)\', $string)){ 
    return $string;
}
相关标签:
8条回答
  • 2020-12-04 13:52

    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.';
    }
    
    0 讨论(0)
  • 2020-12-04 13:54

    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.

    0 讨论(0)
提交回复
热议问题