We have some string $text="Here are some text. The word is inside of the second sentence.";
and $word="word";
How to get $sentence="The word is inside of the second sentence";
- the first sentence that contains " ".$word." "
Of course some assumptions should be made. One of them is that all sentences are finished with ".\r\n"
or "!\r\n"
or ". "
or "! "
.
P.S. We are sure strpos($text," ".$word." ")!==false
Your text:
$txt = "word word word different. different word word word. word word word ending. word word word";
My word is 'different':
$word = "different";
Let us do a preg match:
$c=preg_match("/(\.|^)([^\.]*?".$word."[^\.]*(\.|$))/",$txt,$match);
If it is successful show the second group which holds the sentence:
if($c!==false and count($match) > 0 )
echo( $match[2]) ;
This will return the first occurence. If you want all use preg_match_all.