简体   繁体   中英

PHP digits to string for preg_match

Thanks in advance, I feel like I'm overlooking something very simple. I have some numerical zip codes that I need to run through a function...however, I need to validate that the input is a five digit string. But, no matter how I try to cast the number to string, it's failing. Is there some other way I should be encoding or formatting?:

<?php
$code=07307;
$wrapped_code='07307';
$castcode=(string)$code;
$strcode=''.$code;

echo (preg_match('/^\d{5}$/', $code))?'success with code<br/>':'code failed, saw:'.$code."<br/>";
echo (preg_match('/^\d{5}$/', $wrapped_code))?'success with wrapped_code<br/>':'wrapped_code failed, saw:'.$wrapped_code."<br/>";
echo (preg_match('/^\d{5}$/', $castcode))?'success with castcode<br/>':'castcode failed, saw:'.$castcode."<br/>";
echo (preg_match('/^\d{5}$/', $strcode))?'success with strcode<br/>':'strcode failed, saw:'.$strcode."<br/>";
?>

Try this code:

echo 07307;

You will find, counter-intuitively, that you get the result 3783 . This is because numbers starting in 0 are treated as octals, that is, in base 8. So when you cast 07307 to a string, you get "3783" . If leading zeros are important, you should be using a string in the first place.

根据你所说的你想要实现的,我认为你最好使用is_numericstrlen ,因为is_numeric检查变量是数字还是数字字符串。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM