我需要创建正则表达式,以确保用户输入的数字包括4位数字,即使第一个数字为0 .
-
0001
应该是真的 . -
00020
应该是假的 . -
030
应该是假的 .
这个正则表达式应该包含在一个类中,当我使用时: /^\d{4}$/ 如果数字以0开头则不起作用 . (自动更改为int并删除零..) . 如果我把数字放在“”它可以工作,但我想要更好的正则表达式 .
如何在数字的开头接受0来编写正则表达式?
谢谢,这是我的代码:
public function set_id($num){
$preg = "/^[0-9]{4}$/";
if(preg_match($preg, $num))
{$this->id = $num;}
else {echo "<b>ID</b> can not accept less then 4 digit number!";}
}
public function get_id(){
return $this->id;
}
}
$a = new Business();
$a->set_id(0012);
echo $a->get_id();
3 回答
尝试使用:
结果:
正则表达式适用于字符串,而不是数字 . 因此,如果已删除前导零,则表示您的输入字符串已被解析为数字 . 你需要阻止它发生 - 正则表达式本身是正确的和works just fine with leading zeroes .
因为php对象是dimamicly而且'123'(String)等于123(int),所以My field总是会改变,除非我使用verbumSapienti解决方案 .