Substr causing problems if it cuts an html tag in half...

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
Citizen
Forum Contributor
Posts: 300
Joined: Wed Jul 20, 2005 10:23 am

Substr causing problems if it cuts an html tag in half...

Post by Citizen »

I have a bit of code and I only want the first 25 characters to show.. let say....

Code: Select all

$content = "Hello world <p> with more than 25 characters";

$content = substr("$content", 0, 25);

echo"$content";
Will echo the first 25 characters with the html with no problems.

However....


If my first 25 characters are the first part of a peice of html code.... like....

Code: Select all

$content = "<img src='img.gif' alt='really long alt text' title='really long title text' />";

$content = substr("$content", 0, 25);

echo"$content";
This displays the image but messes up all of the rest of the html on the page until we get to another peice of code that closes the image's title or alt. Is there a safer way to display only the first 25 characters?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

For showing the first snipplet of a news story that may potentially have html, to be safe I run the code through strip_tags()

Some days I wish my regex was better :wink:
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

There's a smarter form of strip_tags() (using regex) found from Useful Posts. ;)
Sloth
Forum Newbie
Posts: 18
Joined: Thu Dec 07, 2006 7:29 pm

Post by Sloth »

I just woke up so my explanation might be pretty bad (Hey, what else is new? )

This is a regex to grab w/e is in tags

Code: Select all

<[^<>]+>
1st thing to do is to run strip_tags on the string, to clear out unwanted tags (like <p>,<div> etc etc).
e.g.

Code: Select all

$content = "Hello world <p> with more than 25 characters"; 
$content = strip_tags($content, "<img>");
Then run the regex and get the results.

Use strstr to get the insertion point, if its within the 1st 25 chars then include it as well. Alternatively, you could exclude it from the 'character count' of 25 to prolly get a more accurate teaser
Post Reply