Reputation: 11
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
Can someone please help to finalize this last part ?
Upvotes: 0
Views: 332
Reputation: 15464
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
Upvotes: 0
Reputation: 623
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.
Upvotes: 1