Php 获取带空格的字符串前后的单词
我试图用正则表达式在一个特定单词前后检索5个单词。我的代码如下Php 获取带空格的字符串前后的单词,php,regex,Php,Regex,我试图用正则表达式在一个特定单词前后检索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>
$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);
我希望字符串122-4555白色1455-789黄色,而不是结果数组中的4555白色1455-789黄色。对于像1455-789这样的单词,它认为1455是一个单词,789是另一个单词。我怎样才能得到准确的单词
有人能帮我修一下吗?提前感谢。数字之间的
\w
无法匹配-
,因此正则表达式无法从预期位置获取预期的子字符串
你应该用(?:\s+\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})~'
看
这样,您将匹配关键字前后任何0到5个空格分隔的非空白块
见:
$str='111-37774蓝色 111-1566红色 122-4555白色 1455-789黄色 最低订单适用。这是一个用于测试的字符串。;
$regexForPattern='/((?:\S+\S+{0,5})最小值\b((?:\S+\S+{0,5})/i';
$nstr=修剪(预替换('.]+>'.'.$str));
echo$nstr。“\n”;
preg_match_all($regexForPattern、$nstr、$patternMatches);
打印(模式匹配);
可能,您希望将(?:\w+\s*){0,5}
替换为(?:\s+\s+{0,5}
和(?:\w*\w+{0,5}
替换为(?:\s+\s+{0,5}
),您还可以使用选择子字符串索引将其推回到SQL层-可能对您来说更简单,请参阅以下参考资料-BTW,这是一把regex小提琴-@WiktorStribiżew..谢谢..它起作用了。
'~((?:\S+\s+){0,5})minimum\b((?:\s+\S+){0,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 ='/((?:\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);