php preg匹配忽略空白的字符串

php preg匹配忽略空白的字符串,php,regex,preg-match,Php,Regex,Preg Match,您好,我需要更改此表达式,使其忽略空白 preg_match("/([a-zA-Z\s]{2,}\,\s)+(RED|BLUE|GREEN|BLACK)$/i",$query, $matches)) $query = "Honda Accord, RED" 因此,即使添加了空格,它仍然会获得匹配,例如 $query = " Honda Accord , RED " 基本上我需要的比赛回到本田雅阁,红色与正确的间距。如您所见,im no regexp expert:)

您好,我需要更改此表达式,使其忽略空白

preg_match("/([a-zA-Z\s]{2,}\,\s)+(RED|BLUE|GREEN|BLACK)$/i",$query, $matches))

$query = "Honda Accord, RED"
因此,即使添加了空格,它仍然会获得匹配,例如

$query = "   Honda    Accord   ,    RED   "
基本上我需要的比赛回到本田雅阁,红色与正确的间距。如您所见,im no regexp expert:)

提前谢谢

$query = "   Honda    Accord   ,    RED   "; 
$query = trim($query); // remove spaces at the ends //
$query = preg_replace('/\s+/', ' ', $query); // make sure there aren't multiple spaces //
$query = preg_replace('/\s?,\s?/', ', ', $query); // enforce the 'word, word' format //
preg_match("/([a-zA-Z\s]{2,}\,\s)+(RED|BLUE|GREEN|BLACK)$/i",$query, $matches);

这将格式化您的字符串,使其具有标准格式,但如果您只想获得匹配项,只需在需要的地方添加
\s*

您需要在颜色之前和之后以及开始时使用空格:

^\s*([a-zA-Z\s]{2,},\s)+\s*(RED|BLUE|GREEN|BLACK)\s*$

谢谢,不太对,但我已经解决了。我已经做了修剪($query)–preg_匹配有效,但技巧是在之后而不是之前对$matches进行preg_准备。啊!我对它进行了测试,你提供的例子在这个表单中运行良好。再次感谢Alin是的,它运行良好,但我也有像福特、瑞德这样的查询,所以我必须让它也运行良好。我忘了。