Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php regex number and + sign only

Tags:

regex

php

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.

like image 205
cyberfly Avatar asked Apr 04 '11 03:04

cyberfly


People also ask

How to preg_ match in PHP?

PHP preg_match() Function $str = "Visit W3Schools"; $pattern = "/w3schools/i"; echo preg_match($pattern, $str);

What is the purpose of preg_ match() regular expression in PHP?

The preg_match() function will tell you whether a string contains matches of a pattern.

What does preg_ match return?

preg_match() returns 1 if the pattern matches given subject , 0 if it does not, or false on failure. Warning. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false .


2 Answers

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
like image 181
Mikel Avatar answered Oct 04 '22 17:10

Mikel


<?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).

like image 36
nonopolarity Avatar answered Oct 04 '22 18:10

nonopolarity