duanmo7075 2017-02-13 15:03
浏览 71

如何使用character_limiter或word_limiter

I'm PHP newbie and can't find a solution for this:

My website prints correctly a product description, which is sometimes very long. Therefore I would like to limit the text to e.g. 100 words and then display "read more..." which would initiate a java script to display the rest of the text.

Here's what I currently have and what works fine so far without text limitation:

<?php echo nl2br($property->description(null, null, true)); ?>

And here's what I was advised to do:

<?php $long_text = ($property->description(null, null, true)); // STRING!
$word_limit = 250; //your word limit, Int
$output = "";
$parts = explode( " ", $long_text );
foreach( $parts as $index=>$word ){
  $output .= "$word ";
  if( intval( $index ) >= intval( $word_limit ) ){
$output .= "READ MORE LINK";
break;
  }
}
echo $output;
?>

As a result the script limits the text indeed to 250 words, but

  1. all line breaks and blank lines are ignored
  2. "READ MORE..." is just plain text - not a link. I would need the code to call a javascript, to print the rest of the text on the same page.

Can someone please help to finalize this last part ?

  • 写回答

2条回答 默认 最新

  • donglin7383 2017-02-13 15:52
    关注

    Here is a simple sample code that would do the trick

    $long_text = "Your very long description"; // STRING!
    $word_limit = 100; //your word limit, Int
    
    $output = "";
    $parts = explode( " ", $long_text );
    foreach( $parts as $index=>$word ){
      $output .= "$word ";
      if( intval( $index ) >= intval( $word_limit ) ){
        $output .= "READ MORE LINK";
        break;
      }
    }
    echo $output;
    

    What it does is make an array of words, and when it hits the limit count of words it adds the "Read more link" and exits the loop, then echoes the output. It is not the most efficient solution but I hope it structures your problem well enough to aid in solving the problem.

    评论

报告相同问题?

悬赏问题

  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图