Possible Duplicate:
How to Truncate a string in PHP to the word closest to a certain number of characters?
How can I shorten a string to a maximum of 140 chars without slicing through a word.
Take the following string:
$string = "This is an example string that contains more than 140 characters. If I use PHPs substring function it will split it in the middle of this word."
Using substr($string, 0, 140)
we would get something like this:
This is an example string that contains more than 140 characters. If I use PHPs substring function it will split it in the middle of this wo
Notice it sliced through the word "word".
What I need is to be able to shorten a string while preserving entire words but without going over 140 characters.
I did find the following code but even though it will preserve entire words, it does not guarantee that the entire string does not go over the 140 char limit:
function truncate($text, $length) {
$length = abs((int)$length);
if(strlen($text) > $length) {
$text = preg_replace("/^(.{1,$length})(\s.*|$)/s", '\\1...', $text);
}
return($text);
}
The length of the string can be limited in PHP using various in-built functions, wherein the string character count can be restricted. Approach 1 (Using for loop): The str_split() function can be used to convert the specified string into the array object.
Cutting a string to a specified length is accomplished with the substr() function. For example, the following string variable, which we will cut to a maximum of 30 characters. $string = 'This string is too long and will be cut short.
Make a loop at the end of the string After cutting the string at the proper length, take the end of the string and tie a knot at the very end, then fold the string over and tie a loop, about the same size as the original loop (about 2cm in diameter).
function limit_text($text, $limit) { if (str_word_count($text, 0) > $limit) { $words = str_word_count($text, 2); $pos = array_keys($words); $text = substr($text, 0, $pos[$limit]) . '...'; } return $text; } echo limit_text('Hello here is a long sentence that will be truncated by the', 5);
If the string is too long, you can first use substr to truncate the string and then a regular expression to remove the last full or partial word:
$s = substr($s, 0, (140 - 3));
$s = preg_replace('/ [^ ]*$/', ' ...', $s);
Note that you have to make the original shorter than 140 bytes because when you add the ... this could increase the length of the string beyond 140 bytes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With