我目前有两个正则表达式匹配。我需要匹配其中任何一个
我目前正在使用此代码:
$string = '000.400.101';
$regex1 = "^(000\.000\.|000\.100\.1|000\.[36])";
$regex2 = "^(000\.400\.0|000\.400\.100)";
$result = (preg_match('/'.$regex1.'/', $string) ||
preg_match('/'.$regex2.'/', $string)) ? 1 : 0 ;
我想缩短它并清理一下。以下是相同的:
$result = (preg_match('/'.$regex1.'|'.$regex2.'/', $string)) ? 1 : 0 ;
答案 0 :(得分:3)
您可以尝试将所有内容合并到以下单个正则表达式中:
000\.(?:[36]|000\.|100\.1|400\.(?:0|100))
$result = preg_match('/000\.(?:[36]|000\.|100\.1|400\.(?:0|100))/', $string) ? 1 : 0;
和here is a link到PHP的演示,显示代码有效。
顺便说一下,如果你一般需要正则表达式匹配IP地址,我认为这个一般性问题应该已经在Stack Overflow和PHP中得到很好的解决,你应该四处寻找可以帮助你的东西。< / p>