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 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图