从string中获得前100个字符,尊重整个单词

这里我曾经问过类似的问题,但是我需要知道这个小小的调整是否可行。 我想缩短一个string为100个字符,并使用$small = substr($big, 0, 100); 这样做。 然而,这只是前100个字符,并不在乎是否分裂了一个字。

有什么办法可以使string的前100个字符,但要确保你不要打破一个字?

例:

 $big = "This is a sentence that has more than 100 characters in it, and I want to return a string of only full words that is no more than 100 characters!" $small = some_function($big); $small = "This is a sentence that has more than 100 characters in it, and I want to return a string of only" 

有没有办法使用PHP做到这一点?

所有你需要做的是使用:

 $pos=strpos($content, ' ', 200); substr($content,0,$pos ); 

就在这里。 这是我几年前从不同论坛上向用户借用的function,所以我不能赞扬它。

 //truncate a string only at a whitespace (by nogdog) function truncate($text, $length) { $length = abs((int)$length); if(strlen($text) > $length) { $text = preg_replace("/^(.{1,$length})(\s.*|$)/s", '\\1...', $text); } return($text); } 

请注意,它会自动添加省略号,如果您不想仅使用'\\1'作为preg_replace调用的第二个参数。

如果将单词定义为“由空格分隔的字符序列”…使用strrpos()查找string中的最后一个空格,缩小到该位置,修剪结果。

当然。 最简单的可能是围绕preg_match写一个包装:

 function limitString($string, $limit = 100) { // Return early if the string is already shorter than the limit if(strlen($string) < $limit) {return $string;} $regex = "/(.{1,$limit})\b/"; preg_match($regex, $string, $matches); return $matches[1]; } 

编辑:更新为不总是包括一个空格作为string中的最后一个字符

只要可能,该函数通过在字边界处添加"..."缩短string。 返回的string最大长度为$len包括"..."

 function truncate($str, $len) { $tail = max(0, $len-10); $trunk = substr($str, 0, $tail); $trunk .= strrev(preg_replace('~^..+?[\s,:]\b|^...~', '...', strrev(substr($str, $tail, $len-$tail)))); return $trunk; } 

示例输出:

  • truncate("Thanks for contributing an answer to Stack Overflow!", 15)
    返回"Thanks for..."
  • truncate("To learn more, see our tips on writing great answers.", 15)
    返回"To learn more..." (逗号也被截断)
  • truncate("Pseudopseudohypoparathyroidism", 15)
    返回"Pseudopseudo..."

这是我的方法,根据埃米尔的回答,但它不会让任何单词使string超过限制,通过使用带有负偏移量的strrpos()。

简单但有效。 我使用与Laravel的str_limit()辅助函数相同的语法,以防您在非Laravel项目中使用它。

 function str_limit($value, $limit = 100, $end = '...') { $limit = $limit - mb_strlen($end); // Take into account $end string into the limit $valuelen = mb_strlen($value); return $limit < $valuelen ? mb_substr($value, 0, mb_strrpos($value, ' ', $limit - $valuelen)) . $end : $value; } 

这对我来说工作正常,我用它在我的脚本

 <?PHP $big = "This is a sentence that has more than 100 characters in it, and I want to return a string of only full words that is no more than 100 characters!"; $small = some_function($big); echo $small; function some_function($string){ $string = substr($string,0,100); $string = substr($string,0,strrpos($string," ")); return $string; } ?> 

祝你好运

最后用完整的单词来说明这个解决scheme

 function text_cut($text, $length = 200, $dots = true) { $text = trim(preg_replace('#[\s\n\r\t]{2,}#', ' ', $text)); $text_temp = $text; while (substr($text, $length, 1) != " ") { $length++; if ($length > strlen($text)) { break; } } $text = substr($text, 0, $length); return $text . ( ( $dots == true && $text != '' && strlen($text_temp) > $length ) ? '...' : ''); } 

input:Lorem ipsum dolor sit amet,consectetur adipisicing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。 如果你想让自己的工作变得更加简单, Duis aute irure dolor in rennederit in voluptate velit esse cillum dolore eu fugiat nulla pariatur。 Excepteur sint occaecat cupidatat non proident,sunt in culpa qui officia deserunt mollit anim id est laborum。

输出:Lorem ipsum dolor sit amet,consectetur adipisicing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。 如果你想让你的孩子成为一个真正的孩子,

这对我来说…

 //trim message to 100 characters, regardless of where it cuts off $msgTrimmed = mb_substr($var,0,100); //find the index of the last space in the trimmed message $lastSpace = strrpos($msgTrimmed, ' ', 0); //now trim the message at the last space so we don't cut it off in the middle of a word echo mb_substr($msgTrimmed,0,$lastSpace) 

这是我的解决scheme:

 /** * get_words_until() Returns a string of delimited text parts up to a certain length * If the "words" are too long to limit, it just slices em up to the limit with an ellipsis "..." * * @param $paragraph - The text you want to Parse * @param $limit - The maximum character length, eg 160 chars for SMS * @param string $delimiter - Use ' ' for words and '. ' for sentences (abbreviation bug) :) * @param null $ellipsis - Use '...' or ' (more)' - Still respects character limit * * @return string */ function get_words_until($paragraph, $limit, $delimiter = ' ', $ellipsis = null) { $parts = explode($delimiter, $paragraph); $preview = ""; if ($ellipsis) { $limit = $limit - strlen($ellipsis); } foreach ($parts as $part) { $to_add = $part . $delimiter; if (strlen($preview . trim($to_add)) <= $limit) { // Can the part fit? $preview .= $to_add; continue; } if (!strlen($preview)) { // Is preview blank? $preview = substr($part, 0, $limit - 3) . '...'; // Forced ellipsis break; } } return trim($preview) . $ellipsis; } 

在你的情况下,这将是(示例):

 $big = "This is a sentence that has more than 100 characters in it, and I want to return a string of only full words that is no more than 100 characters!" $small = get_words_until($big, 100); 
 function truncate ($str, $length) { if (strlen($str) > $length) { $str = substr($str, 0, $length+1); $pos = strrpos($str, ' '); $str = substr($str, 0, ($pos > 0)? $pos : $length); } return $str; } 

例:

 print truncate('The first step to eternal life is you have to die.', 25); 

弦(25)“永恒的第一步”

 print truncate('The first step to eternal life is you have to die.', 12); 

string(9)“第一个”

 print truncate('FirstStepToEternalLife', 5); 

string(5)“第一”

我很抱歉复活这个问题,但我偶然发现这个线程,发现一个小问题。 对于任何人想要一个字符限制,将删除将超过您的给定的限制的话,上述的答案很好。 在我的具体情况下,如果极限落在这个词的中间,我喜欢展示一个词。 我决定分享我的解决scheme,以防其他人正在寻找这个function,并且需要包含文字而不是剪掉它们。

 function str_limit($str, $len = 100, $end = '...') { if(strlen($str) < $len) { return $str; } $str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str)); if(strlen($str) <= $len) { return $str; } $out = ''; foreach(explode(' ', trim($str)) as $val) { $out .= $val . ' '; if(strlen($out) >= $len) { $out = trim($out); return (strlen($out) == strlen($str)) ? $out : $out . $end; } } } 

例子:

  • input: echo str_limit('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', 100, '...');
  • 输出: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore...
  • input: echo str_limit('Lorem ipsum', 100, '...');
  • 输出: Lorem ipsum
  • input: echo str_limit('Lorem ipsum', 1, '...');
  • 输出: Lorem...

这是另一种方式,你可以做到这一点。

 $big = "This is a sentence that has more than 100 characters in it, and I want to return a string of only full words that is no more than 100 characters!" $big = trim( $big ); $small = $big; if( strlen( $big ) > 100 ){ $small = mb_substr( $small, 0, 100 ); $last_position = mb_strripos( $small, ' ' ); if( $last_position > 0 ){ $small = mb_substr( $small, 0, $last_position ); } } echo $small; 

要么

  echo ( strlen( $small ) < strlen( $big ) ? $small.'...' : $small ); 

这也是多字节安全的,即使没有空格也可以工作,在这种情况下,它只是简单地返回前100个字符。 它需要前100个字符,然后从末尾search到最近的单词分隔符。

接受的答案的问题是结果string超过了限制,即它可以超过100个字符,因为strpos将会看到偏移量,所以你的长度总是超过你的限制。 如果最后一个字是长的,像squirreled一样,那么结果的长度将是111(给你一个想法)。

更好的解决scheme是使用wordwrap函数:

 function truncate($str, $length = 125, $append = '...') { if (strlen($str) > $length) { $delim = "~\n~"; $str = substr($str, 0, strpos(wordwrap($str, $length, $delim), $delim)) . $append; } return $str; } echo truncate("The quick brown fox jumped over the lazy dog.", 5); 

这样你可以确定string在你的限制下被截断(并且永远不会超过)

PS如果您打算使用VARCHAR(50)等固定列将数据截断的string存储在数据库中,这一点尤其有用。

PPS请注意wordwrap中的特殊分隔符。 这是为了确保你的string被截断,即使它包含换行符(否则它将截断在你不想要的新行)。

wordwrap按照极限格式化string,用\ n隔开它们,所以我们有小于50的行,ords不是分开的爆炸根据\ n分隔string,所以我们有对应于行列表的数组收集第一个元素。

list($ short)= explode(“\ n”,wordwrap($ ali,50));

请代表Evert ,因为我不能评论或代表。

这里是示例运行

 php > $ali = "ali veli krbin yz doksan esikesiksld sjkas laksjald lksjd asldkjadlkajsdlakjlksjdlkaj aslkdj alkdjs akdljsalkdj "; php > list($short) = explode("\n",wordwrap($ali ,50)); php > var_dump($short); string(42) "ali veli krbin yz doksan esikesiksld sjkas" php > $ali =''; php > list($short) = explode("\n",wordwrap($ali ,50)); php > var_dump($short); string(0) "" 

又一个答案! 我对其他答案并不完全满意,并且想要一个“硬性截断”(如果可能的话,在$ max_characters之前保证字分隔),所以这是我的贡献!

 /** * Shortens a string (if necessary), trying for a non-word character before character limit, adds an ellipsis and * returns. Falls back to a forced cut if no non-word characters exist before. * * @param string $content * @param int $max_characters - number of characters to start looking for a space / break. * @param bool $add_ellipsis - add ellipsis if content is shortened * * @return string */ public static function shorten( $content, $max_characters = 100, $add_ellipsis = TRUE ) { if ( strlen( $content ) <= $max_characters ) { return $content; } // search for non-word characters $match_count = preg_match_all( '/\W/', $content, $matches, PREG_OFFSET_CAPTURE ); // force a hard break if can't find another good solution $pos = $max_characters; if ( $match_count > 0 ) { foreach ( $matches[0] as $match ) { // check if new position fits within if ( $match[1] <= $max_characters ) { $pos = $match[1]; } else { break; } } } $suffix = ( $add_ellipsis ) ? '&hellip;' : ''; return substr( $content, 0, $pos ) . $suffix; } 

##从string获取第一个有限字符##

 <?php $content= $row->title; $result = substr($content, 0, 70); echo $result; ?>