英文:
php | how to allow only plus sign then numbers like +1 or +44 in php
问题
You can use the following regex pattern in PHP to validate phone numbers that include the "+" and "-" signs, as well as numbers:
<?php
$str = '+212600000000';
if (preg_match('/^(\+\d{1,})?\d+(\-\d+)?$/', $str)) {
echo "Valid phone<br>";
echo $str;
/*output*/
// Valid phone
// +212600000000
} else {
echo "Not valid Phone";
}
?>
This pattern allows for the "+" sign to be part of the phone number output and should work for the format you described.
英文:
How can I use regular expressions (regex) to validate phone numbers that include the "+" and "-" signs, as well as numbers?
For example, I want to validate phone numbers in the format of 'country code + phone number', such as '+21260000000' for Morocco or '+447975777666' for the UK.
What regex pattern can I use in PHP to accomplish this validation?
Could you please provide me with a regex pattern in PHP that allows the '+' sign to be part of the phone number output?
because tried so many with perg_match but it comes out with the number without the "+" in the output
<?php
$str = +212600000000 ;
if(preg_match('/^[0-9 +-]+$/', $str)){
echo "Valid phone <br>";
echo $str ;
/*output*/
// Valid phone
// 212600000000
}else{ echo "Not valid Phone"; }
?>
答案1
得分: 1
You should use a pattern which starts with +
, followed by a country code and other digits:
^\+\d+$
Your updated PHP script:
<!-- language: php -->
$str = "+212600000000";
if (preg_match("/^\+\d+$/", $str)) {
echo "Valid phone <br>";
echo $str;
}
else {
echo "Not valid Phone";
}
This prints:
Valid phone <br>+212600000000
英文:
You should use a pattern which starts with +
, followed by a country code and other digits:
^\+\d+$
Your updated PHP script:
<!-- language: php -->
$str = "+212600000000";
if (preg_match("/^\+\d+$/", $str)) {
echo "Valid phone <br>";
echo $str ;
}
else {
echo "Not valid Phone";
}
This prints:
Valid phone <br>+212600000000
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论