cutting a string to the nearest word...

liunx

Guest
i hav another question...
how can you cut a variable to a certain number of characters and to the nearest word? thanks for ne help...can you give us an example?ok, well say i have variable $article that is a long article that goes on for paragraphs and what i want is to have the first 400 characters to the nearest word, so i can post the beginning of the article followed by a "read more" link.ahh I thought that is what it was. something like this

echo substr($article,0,400)."..."; then your link to "read more"

getting to the nearest word is a little more tricker, I wouldn't worry about itI wrote a way to do this for my web site. I'll dig out the code and post it here later.hey mate, how long you gonna hold out on us :P ;)Oops, forgot.
Hang on, I'll go dig up the code now.Ah, okay. What I actually did was to split paragraphs every 6 sentences. With some modification (which I haven't got time to do right now) you could make it split at 400 words.

Here's the code (with a little bit extra). I wrote this over two years ago and that's why I am using ereg functions instead of the nominally faster preg functions which I use today. Just replace the $row['rsrt_desc'] with your string $pattern = "([^\.]*\.){6}"; //Split paragraphs
$replace = "\\0<br /><br />"; //every 6 sentences
$text = $row['rsrt_desc'];
$para = eregi_replace($pattern,$replace,$text);Actually I just quickly thought of a better way to do what you want (wouldn't work with my sentence problem I had)<?php
$text = "This is a phrase that I would like splitting at 10 characters but not mid-word";
$text = substr($text,0,10);
$text = substr($text,0,strrpos($text,' '));
print $text.'...';
?>so
$text = substr($text,0,strrpos($text,' '));

says go until you hit a space? interesting :)The first thing the script does is chop the original string to 400 characters. Then the next substr says "create a string from the first character of the new, 400 character string, upto the position of the first space from the end of the string"

strrpos returns an integer, this is the index position of the character specfied as the second parameter, from the end. (if that all makes sense).
 
Back
Top