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.

5
  • 3
    So you don't really want the first 28 characters but rather the first few words up to length 28. Is that correct? Commented Jul 9, 2009 at 14:45
  • 1
    Yes, I want total 28 characters.. without breaking a word, if it will return me few less characters than 28 without breaking a word, that's fine... Commented Jul 9, 2009 at 14:47
  • 1
    Than make sure that that is clearly specified in the question! Commented Jul 9, 2009 at 14:48
  • @Miky D, earlier I thought it will be more clear by example, anyways edited the post. Commented Jul 9, 2009 at 15:05
  • Related: How to add an ellipsis hyperlink after the first space beyond 170 characters? and Truncate a multibyte String to n chars Commented Mar 20, 2024 at 9:39

13 Answers 13

54

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] . '...'; 
Sign up to request clarification or add additional context in comments.

4 Comments

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?
Could you use str_word_count(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?
I marked this as an answer beacuse its seems to be the best and my problem is solved 100% Thanks @Greg
Is there a similar function for words instead of characters?
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")

Comments

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),' ')."..."); 

Comments

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), " ")); ?> 

Comments

2

This is the simplest solution I know of...

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

Comments

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.

Comments

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.

Comments

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?'...':''); 

Comments

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

Comments

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 

Comments

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...

Comments

-1

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

Comments

-1
substr("some string", 0, x); 

From the PHP Manual

2 Comments

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 :)
Scroll down to the advanced version. us.php.net/manual/en/function.substr.php#73233

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.