Jump to content

function help plz


adamlacombe

Recommended Posts

I want it so if $str has too many characters to limit it, I dont want it to cut off in the middle of a word, and I want "..." at the end of the $str if there is more to it that is hidden.

so I came up with this:

function browsedesclimit($str) 
{ 

if (strlen($str) < 30){
$str = substr($str, 0, 30);

$words = explode(' ', preg_replace("/\s+/", ' ', preg_replace("/(\r\n|\r|\n)/", " ", $str)));
if (count($words) <= 10){
for ($i = 0; $i < 30; $i++){
$str .= $words[$i].' ';
}
	}
return trim($str).'...';
}else{
return $str;
}

}

 

I am not the best with functions so any help at all would be great, thanks!

Link to comment
Share on other sites

Here's my function which seems to be more efficient and flexible. Just pass the string and the max characters to allow. It will reduce it to the first space character before the max limit and add ellipses if needed. The third parameter is optional for setting a custom string for the ellipses

 

function truncateString($string, $length, $ellipse='...')
{
    if (strlen($string) <= $length) { return $string; }
    return array_shift(explode("\n", wordwrap($string, $length))) . $ellipse;
}

$text = "This is a long string with many, many words and it should be truncated";

echo truncateString($text, 45);
//Output: "This is a long string with many, many words..."

 

You should probably trim() the string beforehand.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.