下面的脚本提取$description中的内容摘要,如果在前50个字符中找到句点,它将返回前50个字符和句点。然而,缺陷是,当内容中不存在句点时,它只返回第一个字符。
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个字符后的第一个空格(这样它就不会截断一个单词),并附加"...“
发布于 2011-02-13 06:40:20
你最好的选择是使用正则表达式。这将匹配您的$description直到$maxLength (函数中的第二个参数),但将继续,直到它找到下一个空格。
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;
}
}发布于 2011-02-13 06:08:36
我认为它只需要稍微复杂一点:
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;
}
}发布于 2011-02-13 06:16:38
尝试如下所示:
$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) . '...';
}
}https://stackoverflow.com/questions/4980908
复制相似问题