webmasters
webmasters

Reputation: 5831

Php substr entire words

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).'...';

TY

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

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

Upvotes: 0

Views: 2656

Answers (3)

Evert
Evert

Reputation: 99525

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

Upvotes: 0

jwueller
jwueller

Reputation: 30996

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

Upvotes: 0

Andres SK
Andres SK

Reputation: 10974

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

Upvotes: 1

Related Questions