Hiya! I Have a field in a database, that contains the following text (HTML and text) How do I display only the first 12 words of the field, along with "..." at the end, whilst keeping the formatting in tact? e.g. <br> for new paragraph? Example: The quick brown fox jumps over the lazy dog The quick brown...
you can split the text into an array using the spaces and then loop through the array up to the number of words you want to display
How do I do that? I also need to add "..." if the word limit has been set to less than the total number of words in the database.
for spliting you just do this: $text="<p>The quick brown fox jumps over the lazy dog</p><br /> <p>The quick brown fox jumps over the lazy dog</p>"; $textarray = split(" ",$text); then you loop the array: $num=12 // your choice of how many words for($i=0;$i<$num;$i++) { $newtxt .= $textarray[$i]; } $newtxt .= "..." Thats all
ahh i missed to put that in the code lol here is the corrected version: $num=12 // your choice of how many words for($i=0;$i<$num;$i++) { $newtxt .= $textarray[$i]." "; }
If you limit the words by 9, is it possible to add the "..." to the end of the first "The quick brown fox jumps over the lazy dog", as at the moment, there is no way of telling that the field has been cut short, as there is no "..." whilst the limit is set to 9
Why does the last 3 words from the second "the quick brown fox jumps over the lazy dog" get cut off, also is there anyway to stop it? <?php $text="<p><strong>the quick brown fox jumps over the lazy dog</strong> <br /> <br /> <strong>the quick brown fox jumps over the lazy dog</strong></p>"; $textarray = split(" ",$text); $num=18; // your choice of how many words for($i=0;$i<$num;$i++) { $newtxt .= " ".$textarray[$i]; } echo $newtxt .= "..."; ?> PHP:
Its because of the spaces in your "<br />" tags and between them so change it to "</strong><br/><br/>"
DO NOT USE SPLIT! It has been deprecated and removed from PHP, instead use Explode. also, here is a great way to do what you want: <?php $text="<p><strong>the quick brown fox jumps over the lazy dog</strong> <br /> <br /> <strong>the quick brown fox jumps over the lazy dog</strong></p>"; $num=18; // your choice of how many words $Cut = implode(" ",array_splice(explode(" ",$text),0,$num))); PHP: There you go!