Page 1 of 1

Fixing my "shorten" function...

Posted: Tue Oct 14, 2008 3:27 pm
by seodevhead
Hey guys,

I use a function to shorten the length of a string to less than 300 characters for output to screen, but do it in a way as to not break words. It works wonderfully, however, it does NOT work if there is a carriage return in the first 300 characters. I have a feeling my regular expression is at fault for not allowing carriage returns, and was hoping someone here with some regex knowledge could guide me to the proper modification I need to make:

My Shorten Function:

Code: Select all

# Shortens string to n number of characters, yet does not break words:
function shorten($str, $n, $delim='...')
{
   $len = strlen($str);
   if ($len > $n) {
       preg_match('/(.{' . $n . '}.*?)\b/', $str, $matches);
       return rtrim($matches[1]) . $delim;
   }
   else {
       return $str;
   }
}
How I call the function:

Code: Select all

echo shorten($longString, 300);
Thank you for any help. Much appreciation.

Re: Fixing my "shorten" function...

Posted: Tue Oct 14, 2008 4:11 pm
by prometheuzz
I didn't look at your code too closely, but if the DOT does not match new line characters, then you could try adding the DOT-ALL flag to your regex:

So, instead of:

Code: Select all

'/(.{' . $n . '}.*?)\b/'
try this instead:

Code: Select all

'/(.{' . $n . '}.*?)\b/s'
If that doesn't work, then I apologise for not reading your question with enough attention and I will do so in the morning. It's now past my bed time!
; )

HTH

Re: Fixing my "shorten" function...

Posted: Tue Oct 14, 2008 11:37 pm
by GeertDD
You may also like the text::limit_chars() function I built for Kohana: http://dev.kohanaphp.com/browser/trunk/ ... v=3600#L14

Actually, my regex quite looks like yours. :-)

Re: Fixing my "shorten" function...

Posted: Fri Oct 17, 2008 8:27 am
by seodevhead
Thanks so much guys! Prometheuzz.... that worked! I had no idea I had to use a modifier to make 'dot' see multi-line. You are a life saver!

Re: Fixing my "shorten" function...

Posted: Fri Oct 17, 2008 8:35 am
by prometheuzz
seodevhead wrote:Thanks so much guys! Prometheuzz.... that worked! I had no idea I had to use a modifier to make 'dot' see multi-line. You are a life saver!
You're most welcome!