Closing tags (<b>, <i>) in user-inputted fields

Soldato
Joined
27 Dec 2005
Posts
17,316
Location
Bristol
I'm currently working on a fairly complex dbb, and in one such table/field is a description entered by the user. I want to allow basic HTML (bold, italic, line break) and I'm doing this by replacing all <'s and >'s with ['s and ]'s respectively to disallow all HTML, and then on output converting all [.b]'s into <b>'s and so on.

However I'm wondering how to close tags that are open? A botched way would obviously be just to stick a </b> and </i> at the end of every output, but that's not really good form and won't prevent multiple open tags.

My current thoughts of how to do this are to count the number of [.b]'s and [/b]'s in the var, and if [.b] > [/b] then stick a [/b] on the end for each. Is there an easier/better/simpler way?
 
Stream/Tokenise the string and as you go along, tally the number of opening tags, deducting one for every close tag (unless already at Zero, in case you are given close tags before open tags)

Than the tally will tell you how many opening tags to include.

Edit: infact, just tally both tags.. $i++ when you find one opening tag, $i-- when you find one closing tag. If you have a positive number, append $i closing tags, if you have a negative number, prepend abs($i) opening tags.
 
Last edited:
A gentle suggestion of better semantic markup... replace with <strong></strong> and with <em></em>....

i & b are physical, whereas strong & em are logical. More pragmatically speaking, it will make more sense to a screen reader, and will allow people with custom stylesheets choose their own styling.
 
Back
Top Bottom