Reputation: 2429
My PHP script calls the Freebase API and outputs a paragraph which I then do a little bit of regex and other parsing magic on and return the data to the variable $paragraph
. The paragraph is made up of multiple sentences. What I want to do is return a shorter version of the paragraph instead.
I want to display the first sentence. If it is less than 100 characters then I'd like to display the next sentence until it is at least 100 characters.
How can I do this?
Upvotes: 1
Views: 725
Reputation: 8174
You don't need a regular expression for this. You can use strpos()
with an offset of 99 to find the first period at or after position 100 - and substr()
to grab up to that length.
$shortPara = substr($paragraph, 0, strpos($paragraph, '.', 99) + 1);
You probably want to add a bit of extra checking in case the original paragraph is less than 100 characters, or doesn't end with a period:
// find first period at character 100 or greater
$breakAt = strpos($paragraph, '.', 99);
if ($breakAt === false) {
// no period at or after character 100 - use the whole paragraph
$shortPara = $paragraph;
} else {
// take up to and including the period that we found
$shortPara = substr($paragraph, 0, $breakAt + 1);
}
Upvotes: 2