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

时间:2014-12-06 21:00:58

标签: php text punctuation

所以,我有这个函数可以从大文本中摘录。

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的最佳之处在于它对于新手来说非常简单,但为专业程序员提供了许多高级功能。

有关如何存档的想法吗?

2 个答案:

答案 0 :(得分:2)

与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 );

答案 1 :(得分:1)

我会尝试以下内容并将其放入循环中以便完成所有操作:

// 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);
    }
}