jessica
jessica

Reputation: 1687

Getting sentences that has a certain word and store in array

I have a string, and I need to get all the sentences that have the word "one" in them, and store them in an array. What is the best, and fastest way to do this?

$text = "I have one treehouse. I have one dog. I have two cats."

Needed Results

$array[0] = "I have one treehouse.";
$array[1] = "I have one dog.";

P.S: My example code's string is kind of short, but the kind of string that I need to use this on ranges from 10-100 pages, so what is the fastest and best way to accomplish this?

Upvotes: 0

Views: 39

Answers (1)

gen_Eric
gen_Eric

Reputation: 227270

You should be able to do this with a regular expression, maybe. Something like this:

/[\w\s]+?\bone\s?[\w\s]*?\./g

In PHP, using preg_match_all:

$text = "i have one treehouse. i have one dog. I have two cats.";
$matches = preg_match_all('/[\w\s]+?\bone\s?[\w\s]*?\./', $text, $array);

DEMO: https://eval.in/439700

NOTE: You may need to trim() each of the matches, not sure if I can fix the regex to take care of that.

Upvotes: 1

Related Questions