php:通过sub-substring从字符串中提取子字符串

时间:2013-02-01 14:12:06

标签: php string preg-match substring strpos

我们有一些字符串$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""!\r\n"". ""! "完成。

P.S。我们确信strpos($text," ".$word." ")!==false

3 个答案:

答案 0 :(得分: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!
)

答案 1 :(得分: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);

如果成功,则显示持有该句子的第二组:

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

这将返回第一次出现。如果你想要全部使用preg_match_all。

答案 2 :(得分: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;