php,计算字符并删除超过140个字符的内容

Die*_*oP. 2 php trim count

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

$message= "I am what I am and you are what you are etc etc etc etc"
Run Code Online (Sandbox Code Playgroud)

如果这超过140个字符,那么

$message= "I am what I am and you are what you are..."
Run Code Online (Sandbox Code Playgroud)

这可能吗?怎么样?谢谢

Pek*_*ica 9

如果你想成为"单词敏感"(即在单词的中间没有中断),你可以使用wordwrap().

  • 另请注意,通过将`true`作为第四个参数($ cut):),您可以使用wordwrap对字不敏感:) (2认同)

Gau*_*rav 5

if(strlen($str) > 140){
   $str =  substr($str, 0, 140).'...';
}
Run Code Online (Sandbox Code Playgroud)


OZ_*_*OZ_ 5

这个变体将使用必要的字符集(例如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 .= '...';
}
Run Code Online (Sandbox Code Playgroud)