如何在给定文本中的另一个单词之前或之后获得单个单词。 例如:
Text = "This is Team One Name"
如果在中间词之前没有单词但没有单词,那该怎么办
Text= "This is 100 one Name"
如何获得100
?
如何在One
之前和之后获得Team
和Name
这个词?任何正则表达式模式匹配?
答案 0 :(得分:5)
将其捕捉到group
(?:(?<firstWord>\w+)\s+|^)middleWord(?:\s+(?<secondWord>\w+)|$)
答案 1 :(得分: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);
答案 2 :(得分:2)
<?php
$Text = "This is Team One Name";
$Word = 'Team';
preg_match('#([^ ]+\s+)' . preg_quote($Word) . '(\s[^ ]+)#i', $Text, $Match);
print_r($Match);