tags:

views:

47

answers:

3

I'm developing a website using PHP, MySQL and HTML. In the database, one of the fields is a text that may contain HTML tags such as <b> or <i>, for example.

My problem is that in a specific part of the website (a search section), I wanna display only a 'summary'/substring of this field.

The problem is: when I get a part of this field to display in the page, tags that are not closed influence in the way the rest of the page is displayed.

Two things would solve this problem:

  1. Prevent these specific tags to be shown;
  2. After the field is displayed, I want to close all 'open tags'.

Note that option number one would be much better.

+2  A: 

You can use strip_tags before you display the summary to the user.

Pat
There's a huge disclaimer in the PHP manual: **Warning**Because strip_tags() does not actually validate the HTML, partial, or broken tags can result in the removal of more text/data than expected.
stillstanding
@stillstanding: yes, but as (1) the html here is more or less under controll, and (2) we were only ever going to give a summary, losing some data shouldn't be that much of a problem, it would fit the current need. One would do the `strip_tags` _before_ a `substr` though.
Wrikken
A: 

If the string xhtml compatible? If it is, you could try rolling your own function to match tags, and auto-append closing tags for them at the end.

Use regular expression to look for all opening and closing tags in the string, then loop through the tags. If it encounters an opening tag (without the "/"), then push it into a stack. If it encounters a closing, then pop the top of the stack.

When all the tags have been handled, what's left in the stack will need to be closed. Just pop them off one at a time, and append the closing to the back of your string.

iWantSimpleLife
A: 

I would do it this way::

function to get the string out of DB will return var $return

$tag = strip_tags($return); // will remove tags if exist

print '<p>'$tag'</p>;
Gil Duzanski