如何在 PHP 中只允许加号后跟数字,例如 +1 或 +44。

huangapple go评论70阅读模式
英文:

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

enter image description here

&lt;?php

$str = +212600000000 ;

if(preg_match(&#39;/^[0-9 +-]+$/&#39;, $str)){


echo &quot;Valid phone &lt;br&gt;&quot;; 
echo $str ;
 /*output*/ 
// Valid phone
// 212600000000

}else{ echo &quot;Not valid Phone&quot;; }

?&gt;

答案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 = &quot;+212600000000&quot;;
if (preg_match(&quot;/^\+\d+$/&quot;, $str)) {
    echo &quot;Valid phone &lt;br&gt;&quot;; 
    echo $str ;
}
else {
    echo &quot;Not valid Phone&quot;;
}

This prints:

Valid phone &lt;br&gt;+212600000000

huangapple
  • 本文由 发表于 2023年6月15日 10:25:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76478685.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定