开发者

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 con开发者_StackOverflowtent, 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 "..."


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


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


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


use substr_count to find it and then do substr(,0,50)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜