php, count characters and deleted what is more than 140 characters

橙三吉。 提交于 2019-12-06 05:14:52
if(strlen($str) > 140){
   $str =  substr($str, 0, 140).'...';
}

If you want to be "word sensitive" (i.e. not break in the middle of the word), you can use wordwrap().

This variant will work correct with necessary charset (e.g. utf-8), and will try to cut by space, to not break words:

$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 .= '...';
}

That would be:

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

This is a function that i use quite often

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

you can change the default length to anything you want

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!