我们有一些字符串$text="Here are some text. The word is inside of the second sentence.";和$word="word";
How to get $sentence="The word is inside of the second sentence"; -包含" ".$word." "的第一句话
当然,也应该做一些假设。其中之一是所有句子都以".\r\n"或"!\r\n"或". "或"! "结尾。
附言:我们确信strpos($text," ".$word." ")!==false
发布于 2013-02-01 22:26:45
你可以使用类似这样的东西:
<?php
$text="Here are some text. The word is inside of the second sentence. And the word is also in this sentence!";
$word = 'word';
function getSentenceByWord($text, $word) {
$sentences = preg_split('/(\.|\?|\!)(\s)/',$text);
$matches = array();
foreach($sentences as $sentence) {
if (strpos($sentence,$word) !== false) {
$matches[] = $sentence;
}
}
return $matches;
}
print_r(getSentenceByWord($text, $word));
?>返回:
Array
(
[0] => The word is inside of the second sentence
[1] => And the word is also in this sentence!
)https://stackoverflow.com/questions/14648174
复制相似问题