Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

php

If I have a string in PHP that is obnoxiously long string in PHP and I want to shorten it and then append something to it.

I want to shorten it to the first 6 words or 42 characters, whatever is shorter and then append a '...' to it if it was shortened.

The only case it would not be shortened and the '...' not added would be if it was originally less than 6 words or 42 characters.

How can I do this in PHP?

Logically, I would think I would split the string by white-space and then add each thing before the white-space in an array and take only the first 6 elements out of that array and write them to a new string.

Here is the code I have so far:

str_1 = 'The quick brown fox jumped over the lazy dog';
$words = explode(" ", $str_1);
$counter = 0;
str_2 = '';
foreach($words as $word){
    if($counter < 5){
        //append $words[counter] to str_2;
        counter++;
    }
    else{
        break;
    }
}

I don't know how to do the rest for character count or comparison or appending.

Does anyone have any ideas?

like image 909
Irfan Mir Avatar asked May 24 '13 00:05

Irfan Mir


People also ask

How do I limit 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);

How do you split the first 5 characters of a string?

You can use the substr function like this: echo substr($myStr, 0, 5); The second argument to substr is from what position what you want to start and third arguments is for how many characters you want to return.

How can I get the first 3 characters of a string in PHP?

To get the first n characters from a string, we can use the built-in substr() function in PHP. Here is an example, that gets the first 3 characters from a following string. <? php echo substr("Ok-Google", 0, 3); ?>


2 Answers

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.

like image 62
Marty Avatar answered Nov 11 '22 12:11

Marty


count words (assumes spaces delimit words):

$words = explode(' ', $string);
$wordCount = count($words );

count characters

$length = strlen($string);

together

if($wordCount > 5) {
    $words = array_slice($words, 0, 5);
    $string = implode(' ', $words);
    $length = strlen($string);
}
if($length > 42) {
    $string = substr($string , 0, 42);
}
like image 44
km6zla Avatar answered Nov 11 '22 11:11

km6zla