Skip to content
Advertisement

php regex number and + sign only

I need a php function to validate a string so it only can contains number and plus (+) sign at the front.

Example:

+632444747 will return true
632444747 will return true
632444747+ will return false
&632444747 will return false

How to achieve this using regex?

Thanks.

Advertisement

Answer

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 numbern";
    } else {
        print "$str is not a phone numbern";
    }
}

Output

+632444747 is a phone number
632444747 is a phone number
632444747+ is not a phone number
&632444747 is not a phone number
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement