【问题标题】:php, count characters and deleted what is more than 140 charactersphp,计算字符并删除超过140个字符
【发布时间】:2011-08-25 11:50:27
【问题描述】:

我需要一个 PHP 函数来计算短语的字符数。如果短语长于“140”字符,则此功能应删除所有其他字符并在短语末尾添加三个点。 所以例如我们有。

$message= "I am what I am and you are what you are etc etc etc etc"

如果超过 140 个字符,则

$message= "I am what I am and you are what you are..."

这可能吗?如何? 谢谢

【问题讨论】:

    标签: php count trim


    【解决方案1】:

    那就是:

    /**
     * trim up to 140 characters
     * @param string $str the string to shorten
     * @param int $length (optional) the max string length to return
     * @return string the shortened string
     */
    function shorten($str, $length = 140) {
        if (strlen($str) > $length) {
            return substr($str, 0, $length).'...';
        }
        return $str;
    }
    
    /**
     * trim till last space before 140 characters
     * @param string $str the string to shorten
     * @param int $length (optional) the max string length to return
     * @return string the shortened string
     */
    function smartShorten($str, $length = 140) {
        if (strlen($str) > $length) {
            if (false === ($pos = strrpos($str, ' ', $length))) { // no space found; cut till $length
                return substr($str, 0, $length).'...';
            }
            return substr($str, 0, strrpos($str, ' ', $length)).'...';
        }
        return $str;
    }
    

    【讨论】:

    • 在 if (false === ($pos = strrpos($str, ' ', $length))) 处的 ' if ' 语句中缺少右 ')' 括号
    【解决方案2】:

    此变体可以正确使用必要的字符集(例如 utf-8),并且会尝试按空格剪切,以免断词:

    $charset = 'utf-8';
    $len = iconv_strlen($str, $charset);
    $max_len = 140;
    $max_cut_len = 10;
    if ($len > $max_len)
    {
        $str = iconv_substr($str, 0, $max_len, $charset);
        $prev_space_pos = iconv_strrpos($str, ' ', $charset);
        if (($max_len-$prev_space_pos) < $max_cut_len) $str = iconv_substr($str, 0, $prev_space_pos, $charset);
        $str .= '...';
    }
    

    【讨论】:

    • +1 用于提及 charset/utf-8,所有其他答案都没有考虑。不过没有测试你的代码。
    【解决方案3】:

    这是我经常使用的功能

    function shorten($str,$l = 30){
        return (strlen($str) > $l)? substr($str,0,$l)."...": $str;
    }
    

    您可以将默认长度更改为您想要的任何内容

    【讨论】:

      【解决方案4】:
      if(strlen($str) > 140){
         $str =  substr($str, 0, 140).'...';
      }
      

      【讨论】:

      • 简单而完美。谢谢
      • 如果您希望字符串为 140 个字符并带有 ...,则需要 $str = substr($str, 0, 137) . '...';
      • 你甚至不需要if 声明。
      【解决方案5】:

      如果你想“单词敏感”(即不要在单词中间打断),你可以使用wordwrap().

      【讨论】:

      • 另外请注意,您可以通过将true 作为第四个参数 ($cut) 来使用 wordwrap 来不区分单词:)
      猜你喜欢
      • 1970-01-01
      • 2021-03-21
      • 2020-03-19
      • 2015-09-25
      • 1970-01-01
      • 2016-02-19
      • 1970-01-01
      • 1970-01-01
      • 2018-11-16
      相关资源
      最近更新 更多