My variable $content
contains my text. I want to create an excerpt from $content
and display the first sentence and if the sentence is shorter than 15 characters, I would like to display the second sentence.
I've already tried stripping first 50 characters from the file, and it works:
<?php echo substr($content, 0, 50); ?>
But I'm not happy with results (I don't want any words to be cut).
Is there a PHP function getting the whole words/sentences, not only substr?
Thanks a lot!
I figured it out and it was pretty simple though:
There is one for words - wordwrap
Example Code:
Output:
Here's a function modified from another I found online; it strips out any HTML, and cleans up some funky MS characters first; it then adds in an optional ellipsis character to the content to show that it's been shortened. It correctly splits at a word, so you won't have seemingly random characters;
Input:
<p class="body">The latest grocery news is that the Kroger Co. is testing a new self-checkout technology. My question is: What’s in it for me?</p> <p>Kroger said the system, from Fujitsu,
Output:
The latest grocery news is that the Kroger Co. is testing a new self-checkout technology. My question is: What's in it for me? Kroger said the …
Here's a quick helper method that I wrote to get the first
N
sentences of a given body of text. It takes periods, question marks, and exclamation points into account and defaults to 2 sentences.If I were you, I'd choose to pick only the first sentence.
This would simplyfy things a lot.
For me the following worked: