Page 1 of 1
Shortening a string
Posted: Mon Sep 27, 2010 9:39 pm
by vfm
Hi,
I have a blog page and on this page I only want to show the first 250 characters of the main blog post. So let's say I have a variable called $text and in this contains "The quick brown fox jumps over the lazy dog". But what I want to show is "The quick brown fox..."
How would I go about doing that?
Thanks.
Re: Shortening a string
Posted: Mon Sep 27, 2010 9:52 pm
by Jonah Bron
I've been meaning to work through the logic on this sort of thing for a while. Here's an opportunity
Code: Select all
$text = 'The quick brown fox jumps over the lazy dog';
$limit = 24;
$threshold = 10;
$pos = $limit;
while (!preg_match('/[^a-z]/i', $text[$pos]) && ($limit - $pos) < $threshold) {
$pos--;
}
$excerpt = substr($text, 0, $pos) . '...';
As you can see, you set the max characters. The limit comes down until the last character isn't a letter, and then cuts out the excerpt. That way, it will never break a word. The second condition makes sure it doesn't cut the whole thing out in odd situations.
I'm not quite sure if I got the indexing right: you might need to change it to substr($text, 0, $pos-1).
Edit: fixed missing semicolon

Re: Shortening a string
Posted: Tue Sep 28, 2010 2:26 am
by vfm
Perfect thanks!
Re: Shortening a string
Posted: Tue Sep 28, 2010 12:23 pm
by McInfo
I don't mean to diminish your work, Johan. I solved it differently in this
excerpt function.
Re: Shortening a string
Posted: Thu Sep 30, 2010 8:23 am
by twinedev
One thing to keep in mind is what type of editor is used for writing the blog. Does it take just plain text, or is it like TinyMCE, where it will give you actual formatted HTML.
If it is the later, do not forget to handle the fact that there are tags in there, and they will be counted as characters. While I don't have the exact code right now I use here is the gist of some of the extra steps it takes:
Ok, I have no idea why the list isn't working below, if an admin can edit it and let me know, it would be appreciated...)
- [First, replace any <li> tags with ~*~ (This is not the final replacement, just something most likely NOT to be in the content already)
- Now replace all >< (close of one tag up against the next opening one) with > < (add a space, <p>Sentence one.</p><p>Sentence two.</p> would come out as Sentence one.Sentence two.
- Strip out all HTML tags at this point
- Replace all whitespace characters (and multiples) with a single actual space
- Replace all ~*~ and optional space with the final output you want to display (I use (*))
Now you should have a pretty cleaned up line of text to hand to the code to shorten it.
(Oh, I also have code that will take into consideration things like & as 1 character, I have since found better methods, which is why I didn't put what I have here)
-Greg
Re: Shortening a string
Posted: Thu Sep 30, 2010 9:56 am
by pickle
You could also use
strtok()