How to cut the string without breaking any words

<?php
function Cut($string, $max_length){
	if (strlen($string) > $max_length){
		$string = substr($string, 0, $max_length);
		$pos = strrpos($string, " ");
		if($pos === false) {
				return substr($string, 0, $max_length)."...";
		}
			return substr($string, 0, $pos)."...";
	}else{
		return $string;
	}
}

$string = 'How to cut the string without breaking any words';
echo Cut($string,30);

?>

The output is

function Cut($string, $max_length){
if (strlen($string) > $max_length){
$string = substr($string, 0, $max_length);
$pos = strrpos($string, ” “);
if($pos === false) {
return substr($string, 0, $max_length).”…”;
}
return substr($string, 0, $pos).”…”;
}else{
return $string;
}
}

$string = ‘How to cut the string without breaking any words’;
echo ‘

‘;
echo Cut($string,30);
echo ‘

‘;
?>

PG

Author: insic

Subscribe in my RSS Feed for more updates on Web Design and Development related articles. Follow me on twitter or drop a message to my inbox.

Related Post

Delicious

5 Responses to “How to cut the string without breaking any words”

  1. Very use full code. Thanks RICH.

  2. nice tut just a hint I think you don’t need the ellipsis(…) anymore for that, you can just put the read more text instead somewhat like how google adsense diplays their text in adsense

  3. thank u so much
    it work very good

  4. Muchas gracias…

Leave a Reply