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.
PHP preg_match() Function $str = "Visit W3Schools"; $pattern = "/w3schools/i"; echo preg_match($pattern, $str);
The preg_match() function will tell you whether a string contains matches of a pattern.
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 .
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
<?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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With