Fixing my "shorten" function...

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
seodevhead
Forum Regular
Posts: 705
Joined: Sat Oct 08, 2005 8:18 pm
Location: Windermere, FL

Fixing my "shorten" function...

Post 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.
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Fixing my "shorten" function...

Post 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
User avatar
GeertDD
Forum Contributor
Posts: 274
Joined: Sun Oct 22, 2006 1:47 am
Location: Belgium

Re: Fixing my "shorten" function...

Post 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. :-)
User avatar
seodevhead
Forum Regular
Posts: 705
Joined: Sat Oct 08, 2005 8:18 pm
Location: Windermere, FL

Re: Fixing my "shorten" function...

Post 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!
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Fixing my "shorten" function...

Post 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!
Post Reply