gamblehawk Posted February 26, 2014 Share Posted February 26, 2014 (edited) 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 February 26, 2014 by .josh Quote Link to comment https://forums.phpfreaks.com/topic/286547-extract-sentences-with-specific-words/ Share on other sites More sharing options...
Solution .josh Posted February 26, 2014 Solution Share Posted February 26, 2014 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]); Quote Link to comment https://forums.phpfreaks.com/topic/286547-extract-sentences-with-specific-words/#findComment-1470768 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.