Shotern string ignoring html tags

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
Roaches
Forum Newbie
Posts: 3
Joined: Fri Feb 22, 2008 7:33 pm

Shotern string ignoring html tags

Post by Roaches »

I was wondering how it to shorten a html formated string without it being split in the middle of a html tag. I can get the function to ignore the html tags when counting how many characters are in the string by just using the strip_tags() function, but once the string is passed the length without html tags it'll split some tags that lie between the break point.

For example, if the following string is set to break at 25 characters, it would break the 'a' tag.

Code: Select all

This is example text, <a href='#'>link</a> more random text.
Is the a regex or some other method to ignore all html tags except <p> when using substr() to shorten the string?
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Re: Shotern string ignoring html tags

Post by Kieran Huggins »

http://ca.php.net/strip_tags

You can optionally pass "allowed tags" to include <p>'s, for instance.
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Re: Shotern string ignoring html tags

Post by anjanesh »

Roaches - you got to write your own html parser to handle this.
User avatar
markusn00b
Forum Contributor
Posts: 298
Joined: Sat Oct 20, 2007 2:16 pm
Location: York, England

Re: Shotern string ignoring html tags

Post by markusn00b »

anjanesh wrote:Roaches - you got to write your own html parser to handle this.
Or do what keiran suggested..
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Re: Shotern string ignoring html tags

Post by anjanesh »

markusn00b wrote:
anjanesh wrote:Roaches - you got to write your own html parser to handle this.
Or do what keiran suggested..
markusn00b - what the OP is asking for is something like this

Code: Select all

$s = <<< endl
This is <b style="bad > style">example</b> text, <a href='#'>link</a> more random text
endl;
echo html_left($s, 20);
 
echo html_left($s, 24);
 
html_left($s, 20) should output This is <b style="bad > style">example</b> text because This is example text is 20 chars long.

html_left($s, 24) should output This is <b style="bad > style">example</b> text, <a href='#'>li</a> because This is example text, li is 24 chars long.

He wants to retain the HTML tags when outputting the string.
Post Reply