Jump to content

[SOLVED] Split a paragraph into sentences?


Kane250

Recommended Posts

I'm hoping someone here has a solution for something like this.  Here is what I want to do.  I want to have a user type a paragraph of some sort into a textarea, then when submitted, I want PHP to separate that paragraph into sentences (probably by capturing all the words between periods, exclamation points, etc.), and then have it insert each sentence separately into a table... possible?  Logically it sounds like it would be, but I don't know where to begin with coding it.  Can anyone assist me in getting this started?

 

Thanks in advance!

Link to comment
https://forums.phpfreaks.com/topic/150388-solved-split-a-paragraph-into-sentences/
Share on other sites

you can look into the implode() function which can take a block of text and use a delimiter "." or "!" and split up the text into an array based on that delimiter.

 

there may be another, simpler way to do it as well but i think this would work

 

Correct except for you should be using explode() instead.  It will return an array and you can have multiple delimiters (. ! ? etc...).

You can't have multiple delimiters for explode.  That's what preg_split is for.  But even then, it explodes at the delimiter, so you will get sentences returned without the punctuation marks.  You can take preg_split a step farther and flag it to return them in their own elements with PREG_SPLIT_DELIM_CAPTURE and then run some loop to implode sentence and following punctation mark in the returned array, or just use preg_match_all:

 

preg_match_all('~.*?[?.!]~s',$string,$sentences);

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.