Irfan Mir
Irfan Mir

Reputation: 2175

limit string to first 5 words or first 42 characters in 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?

Upvotes: 6

Views: 11792

Answers (4)

Marty
Marty

Reputation: 39456

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.

Upvotes: 10

Alaksandar Jesus Gene
Alaksandar Jesus Gene

Reputation: 6887

$string = "Your Text Here";
$string_length = 80; // give a random character value including whitespace.
if(strlen($string)>$string_length){
do{
    $new_string = substr($string,0,$string_length);
    $string_length++;
    }while(ctype_graph(substr($new_string,-1)));
  }
else {
   $new_string = $string;
}

echo $new_string;

Upvotes: 0

dave
dave

Reputation: 64657

This will give you the first 6 words, or the first n words where the total length of the words is less than 42.

$words = explode(' ', $string);
$newstring = "";
$i=0;
while (strlen($newstring . $words[$i]) <= 42) && $i < 5) {
   $newstring .= $words[$i];
}
if (strlen($string) > strlen($newstring)) $newstring .= "..."; 

Upvotes: 2

km6zla
km6zla

Reputation: 4887

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

Upvotes: 3

Related Questions