tags:

views:

36

answers:

3

Here's what's NOT working for me:

<?php
 $string = 'I have a dog and his name is <a href="http://www.jackismydog.com"&gt;Jack&lt;/a&gt; and I love him very much because he\'s my favorite dog in the whole wide world and nothing could make me not love him, I think.';
 $limited = substr($string, 0, 100).'...';
 echo $string;
?>

I want to limit the VISIBLE text to 100 characters, but using substr() is also including the non-visible text in the limit (<a href="http://www.jackismydog.com"&gt; and </a>) which takes up 41 of those available 100 characters.

Is there a way to limit the text so that the word "Jack" from the link would be included in the limit, but not <a href="http://www.jackismydog.com"&gt; or </a>?

Edit: I want to keep the link in the string, just not count it's length towards the limit..

A: 

If you want to limit the text part, you need to parse it and check the limit yourself. The easiest way is to:

if ( strlen(strip_tags($string)) > 100 )
{
    // the url inside $url is too big
}
else
{
    // the url inside $url fits
}
TravisO
A: 

Not easily - you could of course use strip_tags to de-htmlise the string, but other than that there's no easy fix.

middaparka
+2  A: 

The easiest way would be to actually parse this into a DOM structure. You could use DOMDocument for that. Then you could simply go through the elements and make any changes to content.

Another approach would be to do a two-pass regex search and replace - first use the regex to find contents of tags, then use the regex to replace the contents with shortened contents. This can be achieved with your usual preg_* functions.

Jani Hartikainen