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

≡放荡痞女 提交于 2019-12-22 12:12:25

问题


I need a PHP function that will count the number of characters of a phrase. If the phrase is longer than "140" character then this function should delete all the other character and add three points at then end of the phrase. So for example we have.

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

IF this is longer than 140 characters, then

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

Is this possible? How? Thank you


回答1:


if(strlen($str) > 140){
   $str =  substr($str, 0, 140).'...';
}



回答2:


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




回答3:


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



回答4:


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



回答5:


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



来源:https://stackoverflow.com/questions/6001690/php-count-characters-and-deleted-what-is-more-than-140-characters

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