2011-02-12 121 views
0

下面的脚本将获取$ description中的内容摘要,并且如果在前50个字符中找到句点,它将返回前50个字符和句点。然而,缺陷是,当内容中没有句点时,它只返回第一个字符。substr strpos帮助

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个字符(所以它不会削减字断)和第一空空间追加” ... “

回答

3

最好的办法是使用正则表达式。这将匹配$ 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; 
    } 
} 
0

使用substr_count找到它,然后做SUBSTR(,0,50)

3

我认为它只是需要一个更复杂一点:

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

这个很好用。谢谢! – 2011-02-12 23:22:37

2

尝试是这样的:

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

这工作正常。任何方式来扩大它,使它不会在中间切断这个词?即前进到下一个空白处,然后附加“...”? – 2011-02-12 22:30:04

+0

修正。 (填充物) – erisco 2011-02-12 22:51:41