开发者

Php substr entire words

开发者 https://www.devze.com 2023-01-27 09:20 出处:网络
How can i substr 20 chars from $xbio and get only complete words? $xbio = \'word1 ord2 word3 word4 and so on\';

How can i substr 20 chars from $xbio and get only complete words?

$xbio = 'word1 ord2 word3 word4 and so on';
echo ''.substr($xbio, 0, 20).'.开发者_如何学Python..';

TY

Found this searching stackoverflow - tell me what do you think please:

<? $xbio = preg_replace('/\s+?(\S+)?$/', '', substr($xbio, 0, 50)); ?>


This is the function i always use:

# advanced substr
function gen_string($string,$min) {
    $text = trim(strip_tags($string));
    if(strlen($text)>$min) {
        $blank = strpos($text,' ');
        if($blank) {
            # limit plus last word
            $extra = strpos(substr($text,$min),' ');
            $max = $min+$extra;
            $r = substr($text,0,$max);
            if(strlen($text)>=$max) $r=trim($r,'.').'...';
        } else {
            # if there are no spaces
            $r = substr($text,0,$min).'...';
        }
    } else {
        # if original length is lower than limit
        $r = $text;
    }
    return $r;
}


preg_match('/^([a-zA-Z0-9 ]{1,20})\\b/', $xbio, $matches);
echo $matches[1];


This is a function that i use for this kind of task:

function truncate($str, $maxLength, $append = '...') {
    if (strlen($str) > $maxLength) {
        $str = substr($str, 0, $maxLength);
        $str = preg_replace('/\s+.*?$/', '', $str); // this line is important for you
        $str = trim($str);
        $str .= $append:
    }

    return $str;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消