首页 文章

php正则表达式编号和仅标志

提问于
浏览
10

我需要一个php函数来验证一个字符串,所以它只能在前面包含数字和加号() .

例:

+632444747 将返回true
632444747 将返回true
632444747+ 将返回false
&632444747 将返回false

如何使用正则表达式实现这一目标?

谢谢 .

2 回答

  • 2
    <?php
    
    var_dump(preg_match('/^\+?\d+$/', '+123'));
    var_dump(preg_match('/^\+?\d+$/', '123'));
    var_dump(preg_match('/^\+?\d+$/', '123+'));
    var_dump(preg_match('/^\+?\d+$/', '&123'));
    var_dump(preg_match('/^\+?\d+$/', ' 123'));
    var_dump(preg_match('/^\+?\d+$/', '+ 123'));
    
    ?>
    

    只有前2个是真的(1) . 其他都是假的(0) .

  • 25

    像这样的东西

    preg_match('/^\+?\d+$/', $str);
    

    测试它

    $strs = array('+632444747', '632444747', '632444747+', '&632444747');
    foreach ($strs as $str) {
        if (preg_match('/^\+?\d+$/', $str)) {
            print "$str is a phone number\n";
        } else {
            print "$str is not a phone number\n";
        }
    }
    

    产量

    +632444747 is a phone number
    632444747 is a phone number
    632444747+ is not a phone number
    &632444747 is not a phone number
    

相关问题