Display first two hundred characters, ignoring HTML markup

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Fritsie
Forum Newbie
Posts: 2
Joined: Wed Jul 12, 2006 2:19 am

Display first two hundred characters, ignoring HTML markup

Post by Fritsie »

Pimptastic | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Hi,

I have been searching on the forum but could not find the answer to the following:
I have a number of newsitems, which I retrieve from a database.  For each newsitem I want to display a teaser on the front page of the site. The teaser should be limited to a maximum length (200 characters). However, the newsitem as retrieved from the database may contain HTML (e.g. <strong> or <br/> or <a link....> etc).  In counting the characters, this markup should be ignored. 
Example, the following string may be retrieved from the database:
This is the <strong>latest</strong> newssample.
The string should count as 26, not as 43.

The structure is something like:

Code: Select all

$maxlength=200
if strlen($newsitem>$maxlength) {
   *** code for limiting text to maximum length, excluding markup ***
   $newsdisplay =$newsdisplay.'. . .'; }
else {
   $newsdisplay =$newsitem ;
}
echo($newsdisplay);
The only possibility I see is going through the $newsitem, character by character to build up $newsdisplay. Upon encountering a '<' the building of the $newsdisplay string stops, while the reading of $newsitem continues. Once a '>' is encountered the build-up of $newsdisplay continues.
To mee this seems very elaborate as and a novice PHP user, I may not be aware of a smarter way of doing this.
I appreciate any suggestion you may have in tackling this issue.

Thanks,
Frits


Pimptastic | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post by JayBird »

Fritsie
Forum Newbie
Posts: 2
Joined: Wed Jul 12, 2006 2:19 am

Post by Fritsie »

Thank you for editting the code. I'm still on the learning curve so I'll make sure I'll do it right next time.

strip_tags() and also some of the user contributions on substr show some interesting stuff and seem to answer my question.

Thanks for the quick feedback.

Cheers,
Frits
Post Reply