Get a sentence from a string. [Fixed]

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Grim...
DevNet Resident
Posts: 1445
Joined: Tue May 18, 2004 5:32 am
Location: London, UK

Get a sentence from a string. [Fixed]

Post 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?
Last edited by Grim... on Wed Jun 01, 2005 8:56 pm, edited 5 times in total.
Grim...
DevNet Resident
Posts: 1445
Joined: Tue May 18, 2004 5:32 am
Location: London, UK

Post by Grim... »

Is that how you spell 'sentence'?
Grim...
DevNet Resident
Posts: 1445
Joined: Tue May 18, 2004 5:32 am
Location: London, UK

Post by Grim... »

Wahey - I have figured out the second part on my own :)

Code: Select all

$sentence = preg_replace(" [\[.*?\]]", "", $sentence);
$sentence = preg_replace(" <\<.*?\>>", "", $sentence);
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Post 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);
Grim...
DevNet Resident
Posts: 1445
Joined: Tue May 18, 2004 5:32 am
Location: London, UK

Post 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!
Post Reply