php中有一个这样的字符串
$str = "192.168.10.1;10.192.10.10;" //Contains repeated ip addresses
我想通过preg_match函数使用正则表达式验证它,但我无法为它创建正则表达式。我创建了以下内容:/^'d{1,3}'.'d{1,3}'.'d{1,3}'.'d{1,3}';'z/
但这只在第一个';'之前有效,而不是在那之后。
Thanks in advance
不是RegEx的解决方案,但使用ip2long函数可以很好地工作:
<?php
$str = "192.168.10.1;10.192.10.10;256.10.10.10";
$ips = explode(";", $str);
foreach ($ips as $ip) {
if (strlen($ip) > 0 && ip2long($ip) === false) {
echo $ip." is not valid.";
}
}
我建议用preg_match_all()
代替preg_match()
。preg_match_all()
捕获主题字符串上找到的所有模式..
,你还应该删除模式中的^
,因为它只匹配主题字符串开头的模式。
我试过这段代码,效果很好:
<?php
$str = "192.168.10.1;10.192.10.10;";
$pattern = "/'d{1,3}'.'d{1,3}'.'d{1,3}'.'d{1,3}';/";
$match = array();
preg_match_all($pattern, $str, $match);
print_r($match);
?>
输出:Array
(
[0] => Array
(
[0] => 192.168.10.1;
[1] => 10.192.10.10;
)
)