views:

1099

answers:

10

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.

A: 

why not try exploding it and getting the first 4 elements of the array?

ghostdog74
A: 

try:

$string='Stack Overflow is as frictionless and painless to use as we could make it.';
$n=28;
$break=strpos(wordwrap($string, $n,'<<||>>'),'<<||>>');
print substr($string,0,($break==0?strlen($string):$break)).(strlen($string)>$n?'...':'');

$string='Stack Overflow';
$n=28;
$break=strpos(wordwrap($string, $n,'<<||>>'),'<<||>>');
print substr($string,0,($break==0?strlen($string):$break)).(strlen($string)>$n?'...':'');
KM
+4  A: 

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

John Kugelman
+2  A: 

Here's one way you could do it:

$str = "Stack Overflow is as frictionless and painless to use as we could make it.";

$strMax = 28;
$strTrim = ((strlen($str) < $strMax-3) ? $str : substr($str, 0, $strMax-3)."...");

//or this way to trim to full words
$strFull = ((strlen($str) < $strMax-3) ? $str : strrpos(substr($str, 0, $strMax-3),' ')."...");
Miky Dinescu
A: 
substr("some string", 0, x);

From the PHP Manual

mcandre
Ya but using this breaks the words sometimes... and I have mentioned in my question that substr is not doing what I want, please read the question again :)
Prashant
Scroll down to the advanced version.http://us.php.net/manual/en/function.substr.php#73233
mcandre
+19  A: 

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] . '...';
Greg
I marked this as answer, but its creating problem when I am using `strip_tags` for string. I have a rich text (html tags included) string and I want to `strip_tags` from that string and then get fixed number of characters. But then its returning blank, because I think with `strip_tags($str)` It vanishes all `/n` due to which explode not able to explode the string properly and it returns blanks string. Any solution to this issue?
Prashant
A: 

I would use a string tokenizer to split the string into words much like this:

$string = "Stack Overflow is as frictionless and painless to use as we could make it.";
$tokenized_string = strtok($string, " ");

Then you can pull out the individual words any way you want.


Edit: Greg has a much better and more elegant way of doing what you want. I would go with his wordwrap() solution.

scheibk
A: 

This is the simplest solution I know of...

substr($string,0,strrpos(substr($string,0,28),' ')).'...';
Travis
A: 

you can use wordwrap.

string wordwrap  ( string $str  [, int $width= 75  [, string $break= "\n"  [, bool $cut= false  ]]] )

-

function firstNChars($str, $n) {
  return array_shift(explode("\n", wordwrap($str, $n)));
}

echo firstNChars("bla blah long string", 25) . "...";

disclaimer: didn't test it.

additionally, if your string contains \ns, it might get broken earlier.

Schnalle
A: 
function truncate( $string, $limit, $break=" ", $pad="...") {

 // return with no change if string is shorter than $limit
 if(strlen($string) <= $limit){
    return $string;
 }

 $string = substr($string, 0, $limit);
 if(false !== ($breakpoint = strrpos($string, $break))){
    $string = substr($string, 0, $breakpoint);
 }
 return $string . $pad;
}
David Morrow