在 preg_match_all 的 2 个单词之间匹配单词
Matching words between 2 words with preg_match_all
我试图找到 "my" 和 "is" 或 "my" 和 "are" 与 preg_match_all 之间的字符串部分,但是对于出于某种原因,它根本找不到任何匹配项。我不确定我做错了什么。请看看我的代码:
$tempText = "My hair is black.";
if ($matches == null) {
$matches = preg_match_all('/my\s+(.+?)\s+is/', $tempText, $matches);
$matches = $matches[1][0];
}
if ($matches == null) {
$matches = preg_match_all('/my\s+(.+?)\s+are/', $tempText, $matches);
$matches = $matches[1][0];
}
echo $matches;
预期结果
hair
实际结果
null
您的大写 "My" 与您的小写 "my" 不匹配,因为它不区分大小写。无论大小写,下面的代码都匹配。
$tempText = "My hair is black.";
if ($matches == null) {
preg_match_all('!my\s(.*?)\sis!is', $tempText, $matches);
$matches = $matches[1][0];
}
if ($matches == null) {
preg_match_all('!my\s(.*?)\sare!is', $tempText, $matches);
$matches = $matches[1][0];
}
echo $matches;
您可以使用这种模式:/my(.*)is/i
我试图找到 "my" 和 "is" 或 "my" 和 "are" 与 preg_match_all 之间的字符串部分,但是对于出于某种原因,它根本找不到任何匹配项。我不确定我做错了什么。请看看我的代码:
$tempText = "My hair is black.";
if ($matches == null) {
$matches = preg_match_all('/my\s+(.+?)\s+is/', $tempText, $matches);
$matches = $matches[1][0];
}
if ($matches == null) {
$matches = preg_match_all('/my\s+(.+?)\s+are/', $tempText, $matches);
$matches = $matches[1][0];
}
echo $matches;
预期结果
hair
实际结果
null
您的大写 "My" 与您的小写 "my" 不匹配,因为它不区分大小写。无论大小写,下面的代码都匹配。
$tempText = "My hair is black.";
if ($matches == null) {
preg_match_all('!my\s(.*?)\sis!is', $tempText, $matches);
$matches = $matches[1][0];
}
if ($matches == null) {
preg_match_all('!my\s(.*?)\sare!is', $tempText, $matches);
$matches = $matches[1][0];
}
echo $matches;
您可以使用这种模式:/my(.*)is/i