【问题标题】:PHP - a more compact function for this process?PHP - 这个过程的更紧凑的功能?
【发布时间】:2013-12-09 14:38:34
【问题描述】:

(PHP) 可以把这个函数做得更紧凑吗?我使用此功能在主页上编写帖子摘要。它在文本的限制长度之后找到第一个空格,因为以避免将单词划分为 ex。我的笔记本很好 -> 总结:我的笔记本..它不应该是我的笔记...

function summary($posttext){
$limit = 60;

$spacepos = @strpos($posttext," ",$limit); //error handle for the texts shorter then 60 ch

while (!$spacepos){
$limit -= 10; //if text length shorter then 60 ch decrease the limit
$spacepos = @strpos($postext," ",$limit);
}

$posttext = substr($posttext,0,$spacepos)."..";

return $posttext;
}

【问题讨论】:

  • 压缩与否:考虑 strops() 返回布尔值 false(未找到)和整数 0(在位置 0 找到)之间的区别
  • 你真的不应该使用错误抑制字符 (@)。这是一种不好的做法,会让您自己更难调试。
  • op 不能用 TRIM 包裹它吗?他正在检查空格,很少需要空格作为字符串的第一个字符。事实上,如果它们在进入数据库的途中被清理,你所说的没有多大意义。除非我误会了。
  • 它不检查字符串的 first 字符中的空格;它正在检查字符串中间的空格(最初是第 60 个字符)......这比第一个字符中的空格更有可能......无论 OP 如何解决检查(针对布尔值进行测试 @987654325 @ 是适当的答案),这是他们需要注意的潜在问题

标签: php function summary


【解决方案1】:

我尝试在不分词的情况下打破

function summary($posttext, $limit = 60){
    if( strlen( $posttext ) < $limit ) {
        return $posttext;
    }
    $offset = 0;
    $split = explode(" ", $posttext);
    for($x = 0; $x <= count($split); $x++){
        $word = $split[$x];
        $offset += strlen( $word );
        if( ($offset + ($x + 1)) >= $limit ) {
            return substr($posttext, 0, $offset + $x) . '...';
        }
    }
    return $posttext;
}

【讨论】:

【解决方案2】:

这样的东西会在最后一个完整的单词上分开而不破坏单词。

function limit_text($text, $len) {
        if (strlen($text) < $len) {
            return $text;
        }
        $text_words = explode(' ', $text);
        $out = null;


        foreach ($text_words as $word) {
            if ((strlen($word) > $len) && $out == null) {

                return substr($word, 0, $len) . "...";
            }
            if ((strlen($out) + strlen($word)) > $len) {
                return $out . "...";
            }
            $out.=" " . $word;
        }
        return $out;
    }

【讨论】:

    【解决方案3】:

    感谢您的帮助。我根据您的建议更正了我的代码。最终版本是这样的:

    function summary($posttext){
    $limit = 60;
    
    if (strlen($posttext)<$limit){
    
    $posttext .= "..";  
    
    }else {
    $spacepos = strpos($posttext," ",$limit);   
    $posttext = substr($posttext,0,$spacepos)."..";
    }
    return $posttext;   
    }
    

    【讨论】:

      猜你喜欢
      • 2015-01-26
      • 2013-11-15
      • 2012-07-23
      • 2018-05-20
      • 2011-05-27
      • 1970-01-01
      • 2011-02-12
      • 2017-07-03
      • 2010-10-26
      相关资源
      最近更新 更多