php – 显示帖子摘录,受字数限制

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 显示帖子摘录,受字数限制脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在我的PHP网站(不是WordPress网站)上主索引我显示两个最新的帖子.事情是在描述它显示整篇文章我发现自己需要显示后摘录可能35字限制.

<?=$line["m_description"]?>

<?
$qresult3 = MysqL_query("SELECT * From t_users WHERE u_id=".$line["m_userid"]." LIMIT 1");
if (MysqL_num_rows($qresult3)<1) { ?>

解决方法:

<?PHP

// just the excerpt
function First_n_words($text, $number_of_words) {
   // Where excerpts are concerned, HTML tends to behave
   // like the PRoverbial ogre in the china shop, so best to strip that
   $text = strip_tags($text);

   // \w[\w'-]* allows for any word character (a-zA-Z0-9_) and also contractions
   // and hyphenated words like 'range-finder' or "it's"
   // the /s flags means that . matches \n, so this can match multiple lines
   $text = preg_replace("/^\W*((\w[\w'-]*\b\W*){1,$number_of_words}).*/ms", '\\1', $text);

   // strip out newline characters from our excerpt
   return str_replace("\n", "", $text);
}

// excerpt plus link if shortened
function truncate_to_n_words($text, $number_of_words, $url, $readmore = 'read more') {
   $text = strip_tags($text);
   $excerpt = first_n_words($text, $number_of_words);
   // we can't just look at the length or try == because we strip carriage returns
   if( str_word_count($text) !== str_word_count($excerpt) ) {
      $excerpt .= '... <a href="'.$url.'">'.$readmore.'</a>';
   }
   return $excerpt;
}

$src = <<<EOF
   <b>;my cool story</b>
   <p>Here it is. It's really cool. I like it. I like lots of stuff.</p>
   <p>I also like to read and write and carry on forever</p>
EOF;

echo first_n_words($src, 10);

echo "\n\n-----------------------------\n\n";

echo truncate_to_n_words($src, 10, 'http://www.GOOGLE.COM');

编辑:添加功能示例并在文本中考虑标点符号和数字

脚本宝典总结

以上是脚本宝典为你收集整理的php – 显示帖子摘录,受字数限制全部内容,希望文章能够帮你解决php – 显示帖子摘录,受字数限制所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: