1

いくつかの文字列が$text="Here are some text. The word is inside of the second sentence.";あり、$word="word";

取得方法$sentence="The word is inside of the second sentence";- を含む最初の文" ".$word." "

もちろん、いくつかの仮定を立てる必要があります。その一つは、すべての文が".\r\n"or "!\r\n"or ". "orで終わること"! "です。

PS 私たちは確信していますstrpos($text," ".$word." ")!==false

4

3 に答える 3

1

次のようなものを使用できます。

<?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!
)
于 2013-02-01T14:26:45.303 に答える
1

あなたのテキスト:

$txt = "word word word different. different word word word. word word word ending. word word word";

私の言葉は「違う」です:

$word = "different";

preg マッチをやってみましょう:

$c=preg_match("/(\.|^)([^\.]*?".$word."[^\.]*(\.|$))/",$txt,$match);

成功した場合は、文を保持する 2 番目のグループを表示します。

if($c!==false and count($match) > 0 )
    echo( $match[2]) ;

これにより、最初の出現が返されます。すべてが必要な場合は、preg_match_all を使用します。

于 2013-02-01T14:26:55.897 に答える
0

正規表現を使用せず、単一の区切り文字「.」を使用:

<?php
$text="Sentence one. Sentence two. Sentence three. Sentence four.";

$word_pos = strpos($text, "Sentence");
$start = strrpos(substr($text, 0, $word_pos), ".");
$end = strpos(substr($text, $word_pos), ".");

$start = $start ? $start + 2 : 0;
$end = $end + $word_pos + 1 - $start;

$sentence = substr($text, $start, $end);

echo $sentence;
于 2013-02-01T14:38:13.853 に答える