How to Truncate a String to the First 20 Words in PHP

How can I truncate a string to the first 20 words in PHP?

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);

Outputs:

Hello here is a long ...

How to Truncate a string in PHP to the word closest to a certain number of characters?

By using the wordwrap function. It splits the texts in multiple lines such that the maximum width is the one you specified, breaking at word boundaries. After splitting, you simply take the first line:

substr($string, 0, strpos(wordwrap($string, $your_desired_width), "\n"));

One thing this oneliner doesn't handle is the case when the text itself is shorter than the desired width. To handle this edge-case, one should do something like:

if (strlen($string) > $your_desired_width) 
{
$string = wordwrap($string, $your_desired_width);
$string = substr($string, 0, strpos($string, "\n"));
}

The above solution has the problem of prematurely cutting the text if it contains a newline before the actual cutpoint. Here a version which solves this problem:

function tokenTruncate($string, $your_desired_width) {
$parts = preg_split('/([\s\n\r]+)/', $string, null, PREG_SPLIT_DELIM_CAPTURE);
$parts_count = count($parts);

$length = 0;
$last_part = 0;
for (; $last_part < $parts_count; ++$last_part) {
$length += strlen($parts[$last_part]);
if ($length > $your_desired_width) { break; }
}

return implode(array_slice($parts, 0, $last_part));
}

Also, here is the PHPUnit testclass used to test the implementation:

class TokenTruncateTest extends PHPUnit_Framework_TestCase {
public function testBasic() {
$this->assertEquals("1 3 5 7 9 ",
tokenTruncate("1 3 5 7 9 11 14", 10));
}

public function testEmptyString() {
$this->assertEquals("",
tokenTruncate("", 10));
}

public function testShortString() {
$this->assertEquals("1 3",
tokenTruncate("1 3", 10));
}

public function testStringTooLong() {
$this->assertEquals("",
tokenTruncate("toooooooooooolooooong", 10));
}

public function testContainingNewline() {
$this->assertEquals("1 3\n5 7 9 ",
tokenTruncate("1 3\n5 7 9 11 14", 10));
}
}

EDIT :

Special UTF8 characters like 'à' are not handled. Add 'u' at the end of the REGEX to handle it:

$parts = preg_split('/([\s\n\r]+)/u', $string, null, PREG_SPLIT_DELIM_CAPTURE);

Truncate a string to first n characters of a string and add three dots if any characters are removed

//The simple version for 10 Characters from the beginning of the string
$string = substr($string,0,10).'...';

Update:

Based on suggestion for checking length (and also ensuring similar lengths on trimmed and untrimmed strings):

$string = (strlen($string) > 13) ? substr($string,0,10).'...' : $string;

So you will get a string of max 13 characters; either 13 (or less) normal characters or 10 characters followed by '...'

Update 2:

Or as function:

function truncate($string, $length, $dots = "...") {
return (strlen($string) > $length) ? substr($string, 0, $length - strlen($dots)) . $dots : $string;
}

Update 3:

It's been a while since I wrote this answer and I don't actually use this code any more. I prefer this function which prevents breaking the string in the middle of a word using the wordwrap function:

function truncate($string,$length=100,$append="…") {
$string = trim($string);

if(strlen($string) > $length) {
$string = wordwrap($string, $length);
$string = explode("\n", $string, 2);
$string = $string[0] . $append;
}

return $string;
}

How can I truncate a string in php without cutting off words?

Before I give you an answer in PHP, have you considered the following CSS solution?

overflow:hidden;
white-space:nowrap;
text-overflow:ellipsis;

This will result in the text being cut off at the most appropriate place and an ellipsis ... marking the cut-off.

If this is not the effect you're looking for, try this PHP:

$words = explode(" ",$input);
// if the first word is itself too long, like hippopotomonstrosesquipedaliophobia‎
// then just cut that word off at 20 characters
if( strlen($words[0]) > 20) $output = substr($words[0],0,20);
else {
$output = array_shift($words);
while(strlen($output." ".$words[0]) <= 20) {
$output .= " ".array_shift($words);
}
}

Truncate a string in php without cutting words

function gen_string($string,$max=20)
{
$tok=strtok($string,' ');
$string='';
while($tok!==false && strlen($string)<$max)
{
if (strlen($string)+strlen($tok)<=$max)
$string.=$tok.' ';
else
break;
$tok=strtok(' ');
}
return trim($string).'...';
}

See it in action: CodePad

Or, using special chars (must have Multibyte String Functions installed):

function gen_string($string,$max=20)
{
$tok=strtok($string,' ');
$string='';
while($tok!==false && mb_strlen($string)<$max)
{
if (mb_strlen($string)+mb_strlen($tok)<=$max)
$string.=$tok.' ';
else
break;
$tok=strtok(' ');
}
return trim($string).'...';
}

limit string to first 5 words or first 42 characters in PHP

This function I made seems pretty tidy:

function truncate($input, $maxWords, $maxChars)
{
$words = preg_split('/\s+/', $input);
$words = array_slice($words, 0, $maxWords);
$words = array_reverse($words);

$chars = 0;
$truncated = array();

while(count($words) > 0)
{
$fragment = trim(array_pop($words));
$chars += strlen($fragment);

if($chars > $maxChars) break;

$truncated[] = $fragment;
}

$result = implode($truncated, ' ');

if ($input == $result)
{
return $input;
}
else
{
return preg_replace('/[^\w]$/', '', $result) . '...';
}
}

Some tests:

$str = 'The quick brown fox jumped over the lazy dog';

echo truncate($str, 5, 42); // The quick brown fox jumped...
echo truncate($str, 3, 42); // The quick brown...
echo truncate($str, 50, 30); // The quick brown fox jumped over the...
echo truncate($str, 50, 100); // The quick brown fox jumped over the lazy dog

It won't cut words in half either, so if a word pushes the character count over the supplied limit, it will be ignored.

Add ... if string is too long PHP

The PHP way of doing this is simple:

$out = strlen($in) > 50 ? substr($in,0,50)."..." : $in;

But you can achieve a much nicer effect with this CSS:

.ellipsis {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}

Now, assuming the element has a fixed width, the browser will automatically break off and add the ... for you.

How do you cut off text after a certain amount of characters in PHP?

May I make a modification to pallan's code?

$truncated = (strlen($string) > 20) ? substr($string, 0, 20) . '...' : $string;

This doesn't add the '...' if it is shorter.

Get first 100 characters from string, respecting full words

All you need to do is use:

$pos=strpos($content, ' ', 200);
substr($content,0,$pos );

How to truncate a string in PHP to the sentence closest to a certain number of characters?

This is what I came up with... you should check if the sentence is longer than the len you are looking for.. among other things like what g13n said. It might be better if the sentence is too short/long to chopping it off and putting "...". Plus, you would have to check/convert whitespace since strrpos will only look for what is given.

$maxlen = 150;
$file = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer malesuada eleifend orci, eget dignissim ligula porttitor cursus. Praesent in blandit enim. Maecenas vitae eleifend est. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Maecenas pulvinar gravida tempor.";
if ( strlen($file) > $maxlen ){
$file = substr($file,0,strrpos($file,". ",$maxlen-strlen($file))+1);
}

if you want to use the same function you have, you can try this:

function shortenString($string, $your_desired_width) {
$parts = preg_split('/([\s\n\r]+)/', $string, null, PREG_SPLIT_DELIM_CAPTURE);
$parts_count = count($parts);

$length = 0;
$last_part = 0;
$last_taken = 0;
foreach($parts as $part){
$length += strlen($part);
if ( $length > $your_desired_width ){
break;
}
++$last_part;
if ( $part[strlen($part)-1] == '.' ){
$last_taken = $last_part;
}
}
return implode(array_slice($parts, 0, $last_taken));
}


Related Topics



Leave a reply



Submit