php regex number and + sign only

<?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'));

?>

only the first 2 will be true (1). the other ones are all false (0).


Something like this

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

Testing it

$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";
    }
}

Output

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

Tags:

Php

Regex