特定のテキスト内の別の単語の前または後に単一の単語を取得するにはどうすればよいですか。例えば :
Text = "This is Team One Name"
たとえば、単語がなく、真ん中の単語の前に数字がある場合はどうなりますか
Text= "This is 100 one Name"
どうすれば入手でき 100
ますか?
の前後にあるという単語はどうすれば取得できますOne
か? 正規表現パターン マッチングはありますか?Team
Name
それらをグループに取り込むことで
(?:(?<firstWord>\w+)\s+|^)middleWord(?:\s+(?<secondWord>\w+)|$)
これはそれを行う必要があります:
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);
<?php
$Text = "This is Team One Name";
$Word = 'Team';
preg_match('#([^ ]+\s+)' . preg_quote($Word) . '(\s[^ ]+)#i', $Text, $Match);
print_r($Match);