因此,在创建从数据库中提取页面信息的动态网站时,我遇到了一个很常见的问题。假设您在首页上有一个滑块,显示 8 个最近的博客/故事帖子。服务器获取每一个的标题、说明和文本字段,但我们不想将文章的全文返回给浏览器,那样会很浪费。所以我猜你会做的是使用递归函数在一定数量的字符处切断文本字段,但我似乎无法弄清楚我做错了什么。这是代码:
$string = strip_tags("<p>Jackson expects to practice on Wednesday for the first time since getting hurt in a season-opening game agains the Chicago Bears. The teams medical advisor says his sprained ankle has healed fast then expected, although he warns to err on the side of caution.</p><p>Coach Andy Reid is optimistic he can get Jackson ready in time for next Monday's square off vs the Detroit Lions, though he states that he doesn't want to take the risk of loosing him for the start of the playoffs in 3 weeks.</p>");
$count = 0;
echo $string."<br />";
function trim_string($string, $max_length, $search_char){
global $count;
$pos = strripos($string, $search_char);
$new_string = substr($string, 0, $pos);
$length = strlen($new_string);
if($length > $max_length){
$count++;
trim_string($new_string, 120, ' ');
}else{
return $new_string;
}
}
$trimmed_string = trim_string($string, 120, ' ');
echo $count."<br />".substr_count($string, ' ')."<br />".$trimmed_string;
如您所见,我正在尝试调试。Count 返回 67,而原始的出现次数是 86,所以我知道它正在工作,但是 $trimmed_string 没有任何回声。
如果有人有任何想法或做这种事情的更好方法,请让我知道!