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 に答える