首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >substr strpos帮助

substr strpos帮助
EN

Stack Overflow用户
提问于 2011-02-13 06:03:41
回答 4查看 577关注 0票数 0

下面的脚本提取$description中的内容摘要,如果在前50个字符中找到句点,它将返回前50个字符和句点。然而,缺陷是,当内容中不存在句点时,它只返回第一个字符。

代码语言:javascript
复制
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;}

我希望这样做:如果没有找到句点,它会返回到50个字符后的第一个空格(这样它就不会截断一个单词),并附加"...“

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-02-13 06:40:20

你最好的选择是使用正则表达式。这将匹配您的$description直到$maxLength (函数中的第二个参数),但将继续,直到它找到下一个空格。

代码语言:javascript
复制
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;
    }
}
票数 3
EN

Stack Overflow用户

发布于 2011-02-13 06:08:36

我认为它只需要稍微复杂一点:

代码语言:javascript
复制
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;
    }
}
票数 3
EN

Stack Overflow用户

发布于 2011-02-13 06:16:38

尝试如下所示:

代码语言:javascript
复制
$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) . '...';
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4980908

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档