【问题标题】:how to chop of a text in a certain length with php?如何用php将文本切割成一定长度?
【发布时间】:2010-01-30 04:16:03
【问题描述】:

我想从数据库中获取一些字段值并将它们呈现在 html 中。

但其中一些比 div 宽度长,所以我想砍掉 if of 并在它们之后添加 3 个点,如果它们长于 30 个字符。

windows vs mac os x-> windows vs m...
threads about windows vista -> threads about win...

我该怎么做?

【问题讨论】:

  • (sidenote) chop() 去除字符串末尾的空格(或其他字符)。更适合您的用例的术语是 truncate。这三个点实际上称为 ellipsis,在技术上只是一个字符:… 作为 HTML 实体。

标签: php string-concatenation


【解决方案1】:

如果您需要多次执行此类功能,请考虑使用此功能:

function truncate($string, $limit, $break = '.', $pad = '...')
{
    // return with no change if string is shorter than $limit
    if(strlen($string) <= $limit) return $string;

    // is $break present between $limit and the end of the string?
    if(false !== ($breakpoint = strpos($string, $break, $limit)))
    {
        if($breakpoint < strlen($string) - 1)
        {
            $string = substr($string, 0, $breakpoint) . $pad;
        }
    }

    return $string;
}

用法:

echo truncate($string, 30);

【讨论】:

    【解决方案2】:

    从你的例子来看,你似乎并不关心保留单词,所以这里是:

    if (strlen($str) > 30)
    {
        echo substr($str, 0, 30) . '...';
    }
    

    【讨论】:

      【解决方案3】:

      如果你使用 Smarty,你可以使用 truncate 修饰符。

      {myLongText|truncate:30:'...':true}
      

      顺便说一句,这样的功能应该存在于任何像样的模板引擎中。

      【讨论】:

        【解决方案4】:

        查看wordwrap(),这应该就是您要查找的内容。

        【讨论】:

          猜你喜欢
          • 2015-05-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-02-01
          • 2015-05-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多