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
JavaScript
x
preg_match('/^+?d+$/', $str);
Testing it
JavaScript
$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
JavaScript
+632444747 is a phone number
632444747 is a phone number
632444747+ is not a phone number
&632444747 is not a phone number