HTML DOM Validator - PHP or JavaScript
I am submitting a form with a text area.
I want the HTML to be posted.
Now I want to check if the user has closed the tags that he placed in the html he posted ... when I display this HTML, broken tags like divs and tables, etc. mess up the whole page display ... any a way to check if a tag is being used correctly in php or javascript?
Any pointers or help would be appreciated.
thank
source to share
You might want to take a look at a PHP tool called HTMLPurifier - there is a demo page if you want to quickly check out what it can do.
It takes a "kind" of HTML as input and produces well-formed HTML as output; this way, you don't force your users to enter well-formed HTML, but you can "fix" what they have typed.
Another nice thing: you can specify which tags and attributes are allowed; which is also good for security:
- for example, you can allow
<p>
and tags<strong>
, but not<script>
. - you can also allow
<a>
+href
; but not<a>
+onclick
For example, here's some poorly formed HTML you can give it:
<p>this is a <strong>test</p>
<script type="text/javascript">alert('glop');</script>
<p>And this is another <em>te<strong>st</em></strong></p>
And here is the well-formed / secure HTML listed as output:
<p>this is a <strong>test</strong></p>
<p>And this is another <em>te<strong>st</strong></em></p>
What changed?
- the tag
<strong>
in the first paragraph was automatically closed - tag
<script>
and its content removed - Fixed order of closing tags
<em>
, and<strong>
in the second paragraph.
This was just a quick example, of course, I hope it helps.
source to share
I'm not really sure what you are trying to accomplish. If you're looking for a rich text editor, try one of the more mature solutions instead of trying to reinvent the wheel /
http://www.queness.com/post/212/10-jquery-and-non-jquery-javascript-rich-text-editors
You will need regular expressions to validate closed tags. This is a little tricky for someone unfamiliar with regex.
Use this search as a starting point: http://www.google.com.kw/search?q=regex+html+tags
source to share