I'd say your approach is a bit too convoluted. It's easier to:
- first get all sentences,
- and then filter this set by your criteria.
E.g:
// keywords to search for
$needles = array('one', 'of', 'here', 'Another');
// input text
$text = 'Start of sentence one. This is a wordmatch one two three four! Another, sentence here.';
// get all sentences (the pattern could be too simple though)
if (preg_match_all('/.+?[!.]\s*/', $text, $match)) {
// select only those fitting the criteria
$hits = array_filter($match[0], function ($sentence) use($needles) {
// check each keyword
foreach ($needles as $needle) {
// return early on first hit (or-condition)
if (false !== strpos($sentence, $needle)) {
return true;
}
}
return false;
});
// log output
print_r($hits);
}
demo: http://ideone.com/pZfOb5
Notes regarding:
if (preg_match_all('/.+?[!.]\s*/', $text, $match)) {
About the pattern:
.+? // select at least one char, ungreedy
[!.] // until one of the given sentence
// delimiters is found (could/should be extended as needed)
\s* // add all following whitespace
array_filter($match[0], function ($sentence) use($needles) {
array_filter
just does what it's name suggests. It returns a filtered version of the input array (here $match[0]
). The supplied callback (the inline function) get's called for each element of the array and should return true/false for whether the current element should be part of the new array.
The use
-syntax allows access to the $needles
-array, which is needed inside the function.