2

如何在给定文本中的另一个单词之前或之后获取一个单词。例如 :

Text = "This is Team One Name"

例如,如果中间单词之前没有单词但只有数字怎么办

Text= "This is 100 one Name"

我怎样才能得到 100

我怎样才能得到这个词之前和之后One,存在TeamName?任何正则表达式模式匹配?

4

3 回答 3

5

通过将它们分组

(?:(?<firstWord>\w+)\s+|^)middleWord(?:\s+(?<secondWord>\w+)|$)
于 2013-06-29T16:00:59.163 回答
4

这应该这样做:

function get_pre_and_post($needle, $haystack, $separator = " ") {
    $words = explode($separator, $haystack);
    $key = array_search($needle, $words);
    if ($key !== false) {
        if ($key == 0) {
            return $words[1];
        }
        else if ($key == (count($words) - 1)) {
            return $words[$key - 1];
        }
        else {
            return array($words[$key - 1], $words[$key + 1]);
        }
    }
    else {
        return false;
    }
}

$sentence  = "This is Team One Name";
$pre_and_post_array = get_pre_and_post("One", $sentence);
于 2013-06-29T16:04:39.907 回答
2
<?php
$Text = "This is Team One Name";
$Word = 'Team';
preg_match('#([^ ]+\s+)' . preg_quote($Word) . '(\s[^ ]+)#i', $Text, $Match);
print_r($Match);
于 2013-06-29T16:10:36.320 回答