Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first x chars from a string, without cutting off the last word?

Tags:

string

php

substr

I have the following string in a variable.

Stack Overflow is as frictionless and painless to use as we could make it.

I want to fetch first 28 characters from the above line, so normally if I use substr then it will give me Stack Overflow is as frictio this output but I want output as:

Stack Overflow is as...

Is there any pre-made function in PHP to do so, Or please provide me code for this in PHP?

Edited:

I want total 28 characters from the string without breaking a word, if it will return me few less characters than 28 without breaking a word, that's fine.

like image 897
djmzfKnm Avatar asked Jul 09 '09 14:07

djmzfKnm


People also ask

How do you find the last word in a string?

Using the substring() Method We'll also use the lastIndexOf() method from the String class. It accepts a substring and returns the index within this string of the last occurrence of the specified substring.

How do I limit text length in PHP?

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.


2 Answers

You can use the wordwrap() function, then explode on newline and take the first part:

$str = wordwrap($str, 28);
$str = explode("\n", $str);
$str = $str[0] . '...';
like image 55
Greg Avatar answered Sep 19 '22 15:09

Greg


From AlfaSky:

function addEllipsis($string, $length, $end='…')
{
    if (strlen($string) > $length)
    {
        $length -= strlen($end);
        $string  = substr($string, 0, $length);
        $string .= $end;
    }

    return $string;
}

An alternate, more featureful implementation from Elliott Brueggeman's blog:

/**
 * trims text to a space then adds ellipses if desired
 * @param string $input text to trim
 * @param int $length in characters to trim to
 * @param bool $ellipses if ellipses (...) are to be added
 * @param bool $strip_html if html tags are to be stripped
 * @return string 
 */
function trim_text($input, $length, $ellipses = true, $strip_html = true) {
    //strip tags, if desired
    if ($strip_html) {
        $input = strip_tags($input);
    }

    //no need to trim, already shorter than trim length
    if (strlen($input) <= $length) {
        return $input;
    }

    //find last space within length
    $last_space = strrpos(substr($input, 0, $length), ' ');
    $trimmed_text = substr($input, 0, $last_space);

    //add ellipses (...)
    if ($ellipses) {
        $trimmed_text .= '...';
    }

    return $trimmed_text;
}

(Google search: "php trim ellipses")

like image 45
John Kugelman Avatar answered Sep 16 '22 15:09

John Kugelman