用空格获取字符串前后的单词

问题描述 投票:2回答:1

我正在尝试使用正则表达式在特定单词之后检索5个单词。我的代码如下。

$str= '<li>111-37774 Blue</li><li>111-1566 Red</li><li>122-4555 White</li><li>1455-789 Yellow</li></ul>Minimum order applies. This is a string for testing.<p>';
$regexForPattern ='/((?:\w+\W\s*){0,5})minimum\b((?:\W*\w+){0,5})/i';   
preg_match_all ($regexForPattern , trim( preg_replace('#<[^>]+>#', ' ', $str) ), $patternMatches); 
print_r($patternMatches);

我想在$str的'minimum'这个词之前和之后说5个单词。

目前我得到的输出为:

Array ( [0] => 
    Array ( [0] => 4555 White 1455-789 Yellow Minimum order applies. This is a ) 
            [1] => Array ( [0] => 4555 White 1455-789 Yellow ) 
            [2] => Array ( [0] => order applies. This is a ) 
)

我期望结果阵列中的字符串122-4555白色1455-789黄色而不是4555白色1455-789黄色。对于像1455-789这样的词,它将1455视为一个词,将789视为另一个词。我怎样才能得到准确的单词?

任何人都可以帮我解决这个问题吗?提前致谢。

php regex
1个回答
1
投票

\w无法匹配数字之间的-,因此正则表达式无法从预期位置获取预期的子字符串。

你应该用(?:\w+\W\s*){0,5}替换(?:\S+\s+){0,5}(?:\W*\w+){0,5}(?:\s+\S+){0,5}

'~((?:\S+\s+){0,5})minimum\b((?:\s+\S+){0,5})~'

regex demo

这样,您将匹配关键字之前和之后的任何0到5个以空格分隔的非空白块。

PHP demo

$str= '<li>111-37774 Blue</li><li>111-1566 Red</li><li>122-4555 White</li><li>1455-789 Yellow</li></ul>Minimum order applies. This is a string for testing.<p>';
$regexForPattern ='/((?:\S+\s+){0,5})minimum\b((?:\s+\S+){0,5})/i';   
$nstr = trim( preg_replace('#<[^>]+>#', ' ', $str));
echo $nstr . "\n";
preg_match_all ($regexForPattern , $nstr, $patternMatches); 
print_r($patternMatches);
© www.soinside.com 2019 - 2024. All rights reserved.