0

Possible Duplicate:
Shorten String in PHP (full words only)
How to get first x chars from a string, without cutting off the last word?

A lot like this question: How to Limit the Length of the Title Tag using PHP

...where the answer is similar to:

 [title]  ?php echo substr( $mytitle, 0, 70 );  [/title]

...but is there any way to accomplish this where the solution does not cut any words in half? So if the word partially exceeds the character count of the limit, the solution would remove the full word, rather than limit it at the character count?

Community
  • 1
  • 1
GlennFriesen
  • 302
  • 4
  • 15

3 Answers3

2

This might get you 95% there, but it's not perfect...

$mytitle = 'How to Limit the Length of the Title Tag using PHP';
$arr = explode(' ',$mytitle);
$string = '';

foreach($arr as $word) {
    if(strlen($string) > 69) break;
    $string .= ' ' . $word;
}

echo $string;
JakeParis
  • 11,056
  • 3
  • 42
  • 65
0

The following is probably one of the easier solutions to implement, but it is not the most efficient.

Take a look at wordwrap which splits your string into multiple lines without breaking words. You can then split it the resulting string by line-shifts using eg. explode("\n", $var, 2) to get the first line, which will be your title.

mqchen
  • 4,195
  • 1
  • 22
  • 21
0

A somewhat entertaining, if non-optimal solution (untested, but you should get the idea):

$wrapped = wordwrap($mytitle, 70, "ENDOFTITLE")
$truncated = substr($wrapped, 0, strpos($wrapped, "ENDOFTITLE"));

Answers to the duplicate questions give better solutions, though.

Nate C-K
  • 5,744
  • 2
  • 29
  • 45