如何在给定文本中的另一个单词之前或之后获取一个单词。例如 :
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);