Web Hosting Talk







View Full Version : Trim long sentense into short


latheesan
03-18-2006, 02:38 PM
lets say im pulling a long article from db and assigning it to the string $str for e.g. like this:

$str = "This article discuss about the upcoming events at our site bla bla bla";

how can i trim the contents of the string $str, so that when i print $str, it looks like this:

"This article discuss about..."

Thanks in advance for your help ;)

hello-world
03-18-2006, 02:51 PM
You can use substr

$newstr = substr($str, 0, 30) . "...";

latheesan
03-18-2006, 03:20 PM
Thanks for the speedy reply.

I have came across this function substr(); on php.net

Its working nicely but its using number of characters to trim the words, which isnt what i was looking for.

E.g.

$str = "We have a nice assorted list of blaa blaa";
$newstr = substr($str, 0, 18) . "...";

and i were to print the contents of the string $newstr, it would look like this:

"We have a nice ***..."

lolzz :emlaugh:

So, is there a way use number of words to workout when to trim the sentense? for e.g. trim everything after 5 words and the output would look something like this:

"We have a nice assorted..."

Dan L
03-18-2006, 03:28 PM
$str = explode(' ',$str);
$str = array_slice($str,0,18);
$str = implode(' ',$str);
echo "$str...";

That could work.

latheesan
03-18-2006, 03:58 PM
Perfecrt DanX ;)

Thanks for your help. Much appreciated.

hello-world
03-18-2006, 03:59 PM
$str = explode(' ',$str);
$str = array_slice($str,0,18);
$str = implode(' ',$str);
echo "$str...";

That could work.

Yup... Just do a

$str = preg_replace("/\s+/", " ", $str); before to make sure that words are single spaced.