Jump to content

extract sentences with specific words


Go to solution Solved by .josh,

Recommended Posts

split from this thread

 

 

How would I make this regex also check for a specific term / string?

 

 

preg_match_all('/(?<=[.?!]|^).*?(?=([.?!])\s{0,3}[A-Z]|$)/s',$content,$matches);
echo "<pre>";
for($i=0;$i<count($matches[0]);$i++)
$result[] = trim($matches[0][$i]).$matches[1][$i];
print_r($result);
}
preg_match_all('/(?<=[.?!]|^).*?(?=([.?!])\s{0,3}[A-Z]|$)/s',$content,$matches);
As in using brackets to specify a string to check is in the sentence

('.$search.')
So, just to make it clear:

-Getting only sentences

-And also making sure the sentences contain a specific string ($search)

 

 

preg_match_all('/(?<=[.?!]|^).*?(?=([.?!])\s{0,3}   == I would assume the ($search) goes somewhere here in the middle ==   [A-Z]|$)/s',$content,$matches);
Edited by .josh
Link to comment
https://forums.phpfreaks.com/topic/286547-extract-sentences-with-specific-words/
Share on other sites

  • Solution

 

Extracting "sentences" is complex and imperfect enough. It would be better to leave your current regex alone and do a 2nd filter.

 

// do the sentence matching
preg_match_all('/(?<=[.?!]|^).*?(?=([.?!])\s{0,3}[A-Z]|$)/s',$content,$matches);
// wrap search term in preg_quote if you are accepting arbitrary data, so as to escape special regex chars
$search = preg_quote('foobar','~'); 
// return sentences that have $search in it. remove the "i" modifier if you want it to be case-sensitive
$sentences = preg_grep('~'.$search.'~i',$matches[0]);
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.