Limiting the Character Count of the Title in Php without splitting words [duplicate]

╄→гoц情女王★ 提交于 2019-12-08 13:43:19

问题


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?


回答1:


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;



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/10505576/limiting-the-character-count-of-the-title-in-php-without-splitting-words

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!