简体   繁体   中英

substr strpos help

The script below pulls a summary of the content in $description and if a period is found in the first 50 characters, it returns the first 50 characters and the period. However, the flaw is, when no period exists in the content, it just returns the first character.

function get_cat_desc($description){
    $the_description = strip_tags($description);
    if(strlen($the_description) > 50 ) 
        return SUBSTR( $the_description,0,STRPOS( $the_description,".",50)+1);
        else return  $the_description;}

I'd like to make it so that if no period is found, it returns up until the first empty space after 50 characters (so it doesn't cut a word off) and appends "..."

I think it just needs to be a little more complicated:

function get_cat_desc($description){
    $the_description = strip_tags($description);
    if(strlen($the_description) > 50 ) {
        if (STRPOS( $the_description,".",50) !== false) {
            return SUBSTR( $the_description,0,STRPOS( $the_description,".",50)+1);
        } else {
            return SUBSTR( $the_description,0,50) . '...';
        }
    } else {
        return  $the_description;
    }
}

Your best bet is to use regular expression. This will match your $description up to $maxLength (2nd argument in function) but will continue until it finds the next space.

function get_cat_desc($description, $max_length = 50) {
    $the_description = strip_tags($description);
    if(strlen($the_description) > $max_length && preg_match('#^\s*(.{'. $max_length .',}?)[,.\s]+.*$#s', $the_description, $matches)) {
        return $matches[1] .'...';
    } else {
        return $the_description;
    }
}

Try something like this:

$pos_period = strpos($the_description, '.');
if ($pos_period !== false && $pos_period <= 50) {
    return substr($the_description, 0, 50);
} else {
    $next_space = strpos($the_description, ' ', 50);
    if ($next_space !== false) {
        return substr($the_description, 0, $next_space) . '...';
    } else {
        return substr($the_description, 0, 50) . '...';
    }
}

使用substr_count找到它,然后执行substr(,0,50)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM