将文本限制为一定数量的字符,但在最后 20 个字符中找到句点时停止


Limit text to a certain number of chars, but stop when a period is found within the final 20 chars

所以,我有这个函数来生成大文本的摘录。

function excerpt( $string, $max_chars = 160, $more = '...' ) {
    if ( strlen( $string ) > $max_chars ) {
        $cut = substr( $string, 0, $max_chars );
        $string = substr( $cut, 0, strrpos( $cut, ' ' ) ) . $more;
    }
  return $string;
}

这对于它的意图来说效果很好 - 它将给定的文本限制为一定数量的字符,而不会削减单词。

下面是一个工作示例

$str = "The best things in using PHP are that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer. Don't be afraid reading the long list of PHP's features. You can jump in, in a short time, and start writing simple scripts in a few hours.";
echo excerpt( $str, 160 );

这将产生以下输出

使用PHP最好的事情是,它对于新手来说非常简单,但为专业程序员提供了许多高级功能。别怕...

但是,我试图弄清楚如果在摘录的最后 20 个字符中找到句点、感叹号或询问标记,如何停止。因此,使用上面的句子,它将产生以下输出:

使用PHP最好的事情是,它对于新手来说非常简单,但为专业程序员提供了许多高级功能。

任何想法如何存档?

与 Fuzzzel 的答案相同的方法,但在第一次匹配时退出循环返回 substr(不带"...")。

function excerpt( $string, $max_chars = 160, $more = '...' ) {
    $punct = array('.', '!', '?');  // array of punctuation chars to stop on
    if ( strlen( $string ) > $max_chars ) {
        $cut = substr( $string, 0, $max_chars );
        $string = substr( $cut, 0, strrpos( $cut, ' ' ) );
        foreach( $punct as $stop ){
            $stop_pos = stripos( $string, $stop, $max_chars - 20 );
            if( $stop_pos !== false){
                return substr( $string, 0, $stop_pos + 1);
            }
        }
    }
  return $string . $more;
}
$str = "The best things in using PHP are that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer! Don't be afraid reading the long list of PHP's features. You can jump in, in a short time, and start writing simple scripts in a few hours.";
echo excerpt( $str, 160 );
我会

尝试以下方法并将其放在一个循环中:

// Define the characters to look for:
$charToCheck = array(".", "!", "?");
// Loop through each character to check
foreach ( $charToCheck as $char) {
    // Gives you the last index of a period. Returns false if not in string
    $lastIndex = strrpos($cut, $char);
    // Checks if character is found in the last 20 characters of your string
    if ( $lastIndex > ($max_chars - 20)) {
        // Returns the shortened string beginning from first character
        $cut = substr($cut, 0, $lastIndex + 1);
    }
}