PHP preg_match for validating 10 digit mobile number - php

I am trying to validate 10 digits mobile number using PHP function preg_match. The below code does not produce any output.
Is it the regex wrong? or I am using it incorrectly.
I was expecting Hi True in the output. if it matches or Hi False if it does not match.
<?php
$value = '9987199871';
$mobileregex = "/^[1-9][0-9]{10}$/" ;
echo "Hi " . preg_match($mobileregex, $value) === 1; // #debug
?>
regex taken from https://stackoverflow.com/a/7649835/4050261

The regex you stated will match eleven digits, not ten. Since all Indian mobile numbers start with 9,8,7, or 6, we can use the following regex:
^[6-9][0-9]{9}$
Here is your code snippet updated:
$value = '9987199871';
$mobileregex = "/^[6-9][0-9]{9}$/" ;
echo "Hi " . preg_match($mobileregex, $value) === 1;
Note that the above regex is still probably far from the best we could do in terms of validation, but it is at least a start.

The following code snippet will check if the mobile number digits are within 10-15 digits including '+' at the start and followed by a non-zero first digit.
Regular expression
"/^[+]?[1-9][0-9]{9,14}$/"
Code snippet
// Validation for the mobile field.
function validateMobileNumber($mobile) {
if (!empty($mobile)) {
$isMobileNmberValid = TRUE;
$mobileDigitsLength = strlen($mobile);
if ($mobileDigitsLength < 10 || $mobileDigitsLength > 15) {
$isMobileNmberValid = FALSE;
} else {
if (!preg_match("/^[+]?[1-9][0-9]{9,14}$/", $mobile)) {
$isMobileNmberValid = FALSE;
}
}
return $isMobileNmberValid;
} else {
return false;
}
}
^ symbol of the regular expression denotes the start
[+]? ensures that a single(or zero) + symbol is allowed at the start
[1-9] make sure that the first digit will be a non zero number
[0-9]{9,14} will make sure that there is 9 to 14 digits
$ denotes the end

$mob = "9513574562";
if(preg_match("/^\d+\.?\d*$/",$mob) && strlen($mob)==10){
echo 1;
}else{
echo 0;
}
preg_match() checking it is integer or not and in strlen() it is checking no of digit in this string. If 2 condition satisfy then it is a 10 digit valid mobile no

for pakistani mobile number the regex code will be the following
^[9][2][3][0-9]{9}$

Related

Regex to avoid equal and sequence digits

I was searching for a regex which matches my requirement. But I couldn't find an exact one .
My requirement is
Add validation check to avoid Phone numbers with:
1) 6 digits equal (e.g. 000000 ; 111111)
2) sequence numbers (7 digits) (e.g.
1234567 ; 7654321)
I tried and got this piece of code finally
if (preg_match('/(\d)\1{5}/', $phone)) {
echo "Invalid Phone number";
}
But it matches only the first case. Hope some one will help me. Thanks in advance!
This is one of those times that I'd break away from regex.
This will perform your expected validation (and includes "around-the-clock" number sequences).
PHP Demo
$phone='000000';
$len=strlen($phone);
$rnd_the_clk='0123456789012345';
if(($len==6 && $phone==str_repeat($phone[0],6)) // length is 6, check only one integer used
||
($len==7 && (strpos($rnd_the_clk,$phone)!==false || strpos($rnd_the_clk,strrev($phone))!==false))){ // length is 7, check sequential
echo "invalid";
}else{
echo "valid";
}

detect if there is any negative number in the input

i am trying to detect in php to check if there is any negative number into the input.
I know if the input is just a number, than it is easy to check, but when there is string with the number, how is it possible to check.
example --- "This is a negative number -99"
So now how is it possible to check that there is a negative number in that line.
I am trying like so, but there is no success ---
$post_data = "This is -12";
if (preg_match('/^\d+$/D', $post_data) && ($post_data < 0)) {
echo "negetive integer!";
} else {
echo 'not working';
}
Expected Result --
Detect if there is any -number like -1, -5, -15 .....
Anyone knows how to solve this problem !!!
Try this:
if (preg_match('/\-[\d]+/', $post_data)){
echo "negetive integer!";
} else {
echo 'not working';
}
First of all, you are using ^ which means that the digit should be at the starting of the string which is not the case here. So we remove it first. then we remove the $ sign as well becasue the negative number can appear anywhere in the string and not just at the end. Next we use a hyphen(-) to tell the regex that the digit should have a minus sign as a prefix to flag it as negative.
Try this:
<?php
$string="9, -1, -5, 11, 19, 22, -8";
$data=explode(",",$string);
$neg_values=array();
foreach($data as $value):
$value = preg_replace('/\s+/', '', $value); // to remove space
if($value < 0):
$neg_values[]=$value;
endif;
endforeach;
?>
now print $neg_values, you will get the required output. :)

Issues with integer operations

function sendSms($toPhone,$message){
$toPhone=intval(trim($toPhone));
if(strlen($toPhone)== 8 && $toPhone{0}==9){
//sending sms
}else{
return "error";
}
}
I am trying to validate mobile numbers for sending SMS. The first line trims the phone number string and then converts it to an integer. In the if statement, I want to make sure that the number length is 8 digits and it begins with 9. This function always goes for the else even if the number is correct( 8 digits and begins with 9). What could be the issue here.
Why not regex?
$valid = preg_match('/^9[0-9]{7}$/', trim($phone));
You can remove from $toPhone all not digits
function sendSms($toPhone,$message){
$_phone = '';
for ($i = 0; $i < strlen($toPhone); $i++)
{
if (is_numeric($toPhone[$i]))
$_phone .= $toPhone[$i];
}
if(strlen($_phone)== 8 && $_phone[0]=='9'){
//sending sms
}else{
return "error";
}
}
After you converted the phone number to an integer with $toPhone=intval(trim($toPhone));,, you can't access the digits in the way you are trying with $toPhone{0}, because you operate on a number and not on a string any more.
See this isolated example:
$number = 987654321;
var_dump($number{0}); //NULL
However, substr would be capable of doing this:
$number = 987654321;
var_dump(substr($number, 0, 1)); //string(1) "9"
Converting a whole number to integer isn't a good idea anyways, because users might enter the number with spaces in between or signs like + and /. Better search for an already existing approach to validate phone numbers.
Take a look here, where the topic "validate mobile phone numbers" is covered in more detail: A comprehensive regex for phone number validation
You convert variable to integer and apparently $toPhone[0] works on strings only.
The same function without intval() works as you wanted.
function sendSms($toPhone, $message)
{
$toPhone = trim($toPhone);
if(strlen($toPhone) == 8 && $toPhone[0] == 9){
//sending sms
} else {
return "error";
}
}

Numeric input validation in PHP

I'm trying to validate an input for Account number in php form. It should contain 8 numbers and '-' optionally. If there is '-' - it should be ignored.
After pressing the Submit button, the warning message suppose to be displayed above the form in case input is invalid.
Please help.
This is what I got so far, but I'm not sure if this is correct and don't know how to display a warning message above the form.
$acctnum= "$acctnum";
if(empty($acctnum)){
echo "You did not enter an account number, please re-enter"; }
else if(!preg_match("\-^[0-9]{8}", $acctnum)){
echo "Your account number can only contain eight numbers. Please re-enter."; }
Thank you!
You don't appear to be trying. No documentation or tutorial will tell you to make a Regex like that. For starters, where are the delimiters? Why is - escaped when it's outside a character class and therefore has no special meaning? What is that ^ doing there?
This should do it:
$acctnum = str_replace("-","",$acctnum);
if( !preg_match("/^\d{8}$/",$acctnum)) echo "Error...";
Since regex are quite expensive I'd go like that instead:
$acctnum = (int) $acctnum; // this automatically ignore the '-'
if ($acctnum < 0) $acctnum = -$acctnum;
$digits = ($acctnum == 0) ? log10($acctnum) + 1 : 1;
if ($digits === 8) { ... }
Split the task in two. First get rid of the "-" with str_replace and then check for the numbers.
$match = preg_match("/^\d{8}$/", str_replace("_", "", $str));
if ($match > 0) {
// Correct
} else {
// incorrect
}

Regular Expression (avoid float numbers)

I want a pattern to create a "is_id()" function to validate user input before mysql query. The pattern most contain ONLY numbers, my problem is avoid the float numbers:
function is_id($id) {
$pattern = "/^[0-9]+/";
if(preg_match($pattern,$id)) {
echo "ok";
} else {
echo "error";
}
}
is_id(0) // error
is_id(-5) // error
is_id(-5.5) // error
is_id(1.5) // ok <-- THIS IS THE PROBLEM
is_id(10) // ok
is_id("5") // ok
is_id("string") // error
$ denotes the end of a line/string to match.
/^[0-9]+$/
You're missing the trailing $ in your pattern. In is_id(1.5) your pattern is matching the 1 and stopping. If you add a trailing $ (as in ^[0-9]+$) then the pattern will need to match the entire input to succeed.
Why use a regex? Why not check types (this isn't as tiny as the regex, but it may be more semantically appropriate)
function is_id($n) {
return is_numeric($n) && floor($n) == $n && $n > 0;
}
is_numeric() verifies that it's either a float, an int, or a number than can be converted.
floor($n) == $n checks to see if it's indeed an integer.
$n > 0 checks to see if it's greater than 0.
Done...
You don't need regex for this, you can use a simple check like so:
function is_id($id)
{
return ((is_numeric($id) || is_int($id)) && !is_float($id)) && $id > -1
}
The output is as follows:
var_dump(is_id(0)); // false - are we indexing from 0 or 1 ?
var_dump(is_id(-5)); // false
var_dump(is_id(-5.5)); // false
var_dump(is_id(1.5)); // false
var_dump(is_id(10)); // true
var_dump(is_id("5")); // true
var_dump(is_id("string")); // false
I favour ircmaxell's answer.

Categories