0
function validCleanHtml( $unclosedString )
{
    preg_match_all( "/<([^\/]\w*)>/", $closedString = $unclosedString, $tags );
    for ( $i = count( $tags[1] ) - 1; $i >= 0; $i-- )
    {
        $tag = $tags[1][$i];
        if ( substr_count( $closedString, "</$tag>" ) < substr_count( $closedString, "<$tag>" ) )
            $closedString .= "</$tag>";
    }
    $validTags = "<em><strong>";
    $validClosedString = strip_tags( $closedString, $validTags );
    return $validClosedString;

}

ok what i want is to enable 2 html, em and strong, is this just secure from xss ? if not how can we secure it ?

2 Answers 2

12

Have you looked at any existing solutions like htmlpurifier? You really don't want to write your own HTML parser - and certainly not with regular expressions.

Sign up to request clarification or add additional context in comments.

1 Comment

I think something like this is the way to go for safehtml. I don't think it is necessary to re-invent the wheel. This is exactly what I was looking for, even though it may not be exactly what the original poster of this question was looking for.
4

I think that strip_tags holds the answer.

https://www.php.net/strip_tags

Rather than enabling certain fields, you could also remove the ones you don't want. Namely: link, style, script, iframe, frame

1 Comment

@Adam, please consider @jasonbar's answer as well. It provides superior filtering options than strip_tags.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.