简体   繁体   English

如何使用character_limiter或word_limiter

[英]How to use character_limiter or word_limiter

I'm PHP newbie and can't find a solution for this: 我是PHP新手,无法为此找到解决方案:

My website prints correctly a product description, which is sometimes very long. 我的网站正确打印了产品说明,有时可能会很长。 Therefore I would like to limit the text to eg 100 words and then display "read more..." which would initiate a java script to display the rest of the text. 因此,我想将文本限制为例如100个单词,然后显示“阅读更多...”,这将启动一个Java脚本来显示其余文本。

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 结果,该脚本实际上将文本限制为250个单词,但是

  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. 我需要代码来调用javascript,以将其余文本打印在同一页面上。

Can someone please help to finalize this last part ? 有人可以帮忙完成最后一部分吗?

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. 它不是最有效的解决方案,但我希望它能很好地解决您的问题,以帮助解决问题。

Do the word-warp and take the 1st line 扭曲文字并走第一行

$text = "The quick brown fox jumped over the lazy dog.The quick brown fox jumped over the lazy dog.The quick brown fox jumped over the lazy dog.The quick brown fox jumped over the lazy dog.The quick brown fox jumped over the lazy dog.The quick brown fox jumped over the lazy dog.The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 100, "<br />\n");
$first_line=explode("<br />\n",$newtext);
echo $first_line[0];

http://phpfiddle.org/main/code/0tqt-a558 http://phpfiddle.org/main/code/0tqt-a558

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM