Page 1 of 1

Get a sentence from a string. [Fixed]

Posted: Wed Jun 01, 2005 7:36 pm
by Grim...
This is probably pretty simple for someone who can use regular expressions.

Basically, I want to take just one sentence from a collection of anything up to (say) 30 sentences contained in one string, so I need a regexp that will find a full stop / period, and work back (or forward, I guess) until it finds another, and strip that out into another string.
However, if there is only one full stop / period (ie. only one sentence in the block of text, or maybe none (if the user can't punctuate properly), it would have to figure that out too, and return the whole lot...

Basically:

Code: Select all

$sentence = preg_strip("lots/of/clever/stuff", $blockoftext);
Then I need to take that sentence and get rid of anything between either square brackets or HTML tags (including the brackets themselves), so if the $sentence was 'Bob was <i>happy</i>.' I'd need to change it to 'Bob was happy.'

Anyone?

Posted: Wed Jun 01, 2005 7:37 pm
by Grim...
Is that how you spell 'sentence'?

Posted: Wed Jun 01, 2005 7:40 pm
by Grim...
Wahey - I have figured out the second part on my own :)

Code: Select all

$sentence = preg_replace(" [\[.*?\]]", "", $sentence);
$sentence = preg_replace(" <\<.*?\>>", "", $sentence);

Posted: Wed Jun 01, 2005 8:21 pm
by Skara
I can't see figuring out where a sentence ends without punctuation, but to just split a string into individual sentences, I'd use something like this...

Code: Select all

preg_match('/[^\.\?!]+?[\.\?!]/',$string,$matches);

Posted: Wed Jun 01, 2005 8:54 pm
by Grim...
That's excellent - I'm counting $matches and using a random number to choose from the array.

I've also added a full stop to the end of each batch of text, in case the user doesn't use puctuation.

I'm using it for the random quote section here: http://www.hsmx.com/ninja/profile.php?user=1 Every time you hit refresh, you get a different thing the user has said.

It works pretty well (sometimes there are oddities, like a " or a ) at the beginning of the quote, but I'll live with them).

Cheers!