I tried to implement very simple html edit text area which has available tags user can input are restricted.
So I needed to implement a validator which detects tags not allowed to use.
The proper (but a bit heavy) implementation approach is using Tidy.
It can validate entire html and also fix and clean up html source!
However in my case using tidy is a bit overkill solution.
Instead of using tidy, I decided to use strip_tags function.
The disadvantage is that the function does not validate html syntax. e.g. inaccurate than using tidy.- "strip_tags function does not actually validate the html, partial or broken tags can result in the removal of more text/data than expected." as the official PHP document says.
Let's show you the code.
function validateOnlyAllowedTags($html, $tags) { $stripped = strip_tags($html, $tags); // if no tags are stripped, the length of html contents should not be changed return strlen($stripped) == strlen($html); }
The function usage is below:
$html = '<h2>Title</h2>' $result = validateOnlyAllowedTags($html, 'h2'); echo($result); // should be true! $result = validateOnlyAllowedTags($html, 'h3'); echo($result); // should be false!Hope this post helps :D
コメント