如何从string中获得前x个字符而不切断最后一个单词?
我有一个variables中的以下string。
堆栈溢出是无摩擦和无痛的使用,因为我们可以做到这一点。
我想从上面的行中获取前28个字符,所以通常如果我使用substr,那么它会给我Stack Overflow is as frictio
这个输出,但我想输出为:
堆栈溢出是...
在PHP中是否有预制的function呢,或者请在PHP中提供这个代码给我?
编辑:
我希望string中的总共28个字符不会被打破一个字,如果它会返回less于28个字符而不会打破一个字,那很好。
您可以使用wordwrap()
函数,然后在换行符上进行爆炸并采取第一部分:
$str = wordwrap($str, 28); $str = explode("\n", $str); $str = $str[0] . '...';
来自AlfaSky :
function addEllipsis($string, $length, $end='…') { if (strlen($string) > $length) { $length -= strlen($end); $string = substr($string, 0, $length); $string .= $end; } return $string; }
来自Elliott Brueggeman博客的另一个更有效的实现:
/** * 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; }
(谷歌search:“PHP修剪省略号”)
以下是你可以做到的一个方法:
$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),' ')."...");
这是我所知道的最简单的解决scheme…
substr($string,0,strrpos(substr($string,0,28),' ')).'...';
这是最简单的方法:
<?php $title = "this is the title of my website!"; $number_of_characters = 15; echo substr($title, 0, strrpos(substr($title, 0, $number_of_characters), " ")); ?>
我会使用一个string标记器将string拆分为如下所示的单词:
$string = "Stack Overflow is as frictionless and painless to use as we could make it."; $tokenized_string = strtok($string, " ");
然后,你可以以任何你想要的方式拉出单词。
编辑:格雷格有一个更好,更优雅的方式做你想做的。 我会用他的wordwrap()解决scheme。
你可以使用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) . "...";
免责声明:没有testing它。
另外,如果你的string包含\n
s,它可能会更早被破坏。
尝试:
$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?'...':'');
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; }
如果你的string有html标签,&nbsp和多个空格,则会出现问题。 以下是我使用的一切:
function LimitText($string,$limit,$remove_html=0){ if ($remove_html==1){$string=strip_tags($string);} $newstring = preg_replace("/(?:\s| )+/"," ",$string, -1); // replace   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; }
用法:
$string = 'My wife is jealous of stackoverflow'; echo LimitText($string,20); // My wife is jealous
使用html:
$string = '<div><p>My wife is jealous of stackoverflow</p></div>'; echo LimitText($string,20,1); // My wife is jealous
这对我来说是完美的
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
它会调整和打破上一个空间没有切词…
为什么不尝试爆炸并获得arrays的前4个元素?
substr("some string", 0, x);
从PHP手册