14

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.

djmzfKnm
  • 26,679
  • 70
  • 166
  • 227

13 Answers13

53

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
  • 316,276
  • 54
  • 369
  • 333
  • 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? – djmzfKnm Feb 25 '10 at 06:20
  • Could you use `str_word_count`(http://uk3.php.net/manual/en/function.str-word-count.php) to check the contents then iterate to the next `$str[]` element if it returns `0`? – Alex Hadley Nov 20 '11 at 14:21
  • I marked this as an answer beacuse its seems to be the best and my problem is solved 100% Thanks @Greg – Humphrey Mar 10 '13 at 09:51
  • Is there a similar function for *words* instead of characters? – Pathros Mar 03 '15 at 22:08
11

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
  • 349,597
  • 67
  • 533
  • 578
3

This is the easiest way:

<?php 
$title = "this is the title of my website!";
$number_of_characters = 15;
echo substr($title, 0, strrpos(substr($title, 0, $number_of_characters), " "));
?>
PachinSV
  • 3,680
  • 2
  • 29
  • 41
3

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),' ')."...");
Mike Dinescu
  • 54,171
  • 16
  • 118
  • 151
2

This is the simplest solution I know of...

substr($string,0,strrpos(substr($string,0,28),' ')).'...';
Travis
  • 4,018
  • 4
  • 37
  • 52
0

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.
  • 101,727
  • 34
  • 178
  • 212
0

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
  • 1,370
  • 3
  • 10
  • 19
0

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.

stefs
  • 18,341
  • 6
  • 40
  • 47
0
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
  • 8,965
  • 4
  • 29
  • 24
0

Problems can arise if your string has html tags, &nbsp and multiple spaces. Here is what I use that takes care of everything:

function LimitText($string,$limit,$remove_html=0){
    if ($remove_html==1){$string=strip_tags($string);}
    $newstring = preg_replace("/(?:\s|&nbsp;)+/"," ",$string, -1); // replace &nbsp with space
    $newstring = preg_replace(array('/\s{2,}/','/[\t\n]/'),' ',$newstring); // replace duplicate spaces
    if (strlen($newstring)<=$limit) { return $newstring; } // ensure length is more than $limit
    $newstring = substr($newstring,0,strrpos(substr($newstring,0,$limit),' '));
    return $newstring;
}

usage:

$string = 'My wife is jealous of stackoverflow';
echo LimitText($string,20);
// My wife is jealous

usage with html:

$string = '<div><p>My wife is jealous of stackoverflow</p></div>';
echo LimitText($string,20,1);
// My wife is jealous
David D
  • 1,269
  • 17
  • 22
0

This's Working for me Perfect

function WordLimt($Keyword,$WordLimit){

    if (strlen($Keyword)<=$WordLimit) { return $Keyword; }
    $Keyword= substr($Keyword,0,strrpos(substr($Keyword,0,$WordLimit),' '));
    return $Keyword;
}

echo WordLimt($MyWords,28);

// OutPut : Stack Overflow is as

it will adjust and break on last Space without cut word...

Hitesh Aghara
  • 186
  • 1
  • 9
-1

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

ghostdog74
  • 327,991
  • 56
  • 259
  • 343
-1
substr("some string", 0, x);

From the PHP Manual

mcandre
  • 22,868
  • 20
  • 88
  • 147
  • 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 :) – djmzfKnm Jul 09 '09 at 14:48
  • Scroll down to the advanced version. http://us.php.net/manual/en/function.substr.php#73233 – mcandre Jul 09 '09 at 15:28