Page 1 of 1

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

Posted: Tue Dec 12, 2006 1:26 pm
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?

Posted: Tue Dec 12, 2006 1:46 pm
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:

Posted: Tue Dec 12, 2006 6:16 pm
by feyd
There's a smarter form of strip_tags() (using regex) found from Useful Posts. ;)

Posted: Tue Dec 12, 2006 6:39 pm
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