i am trying to handle from server side to check the string is in correct format or not for example
$string = "9000010000,9100011000,9000020000 // Its correct pattern
$string = "9000010000,9100011000,9000020000, // Its WRONG Reason comma in last place
$string = ",9000010000,9100011000,9000020000, // Its WRONG Reason comma in first place
$string = ",9000010000,9100011000,,9000020000, // Its WRONG Reason ,,
$string = "9000010000,9100011,9000020000, // Its WRONG because Middle no. is not 10 digit
i already did client side validation through JavaScript using this code
var listIsOk=/^(\d{10},)*\d{10}$/.test(contact_list);
if(listIsOk==true){
alert("success"
}
else {
alert("string is wrong")
}
i want to know how i can achieve this on php thank you in advance
if (preg_match('/^(\d{10},)*\d{10}$/', $string)) {
echo 'success';
} else {
echo 'string is wrong';
}
Start by looking into the php function explode(), which will allow you to split your string into an array of phone numbers. From there you'll need to loop through and look at each one to determine if it's correct.
Related
I am trying to find if a persons name contains any numbers or symbols. I am not very sure how to use preg_match and all the examples online make no sense can someone please explain how i can check if a value has numbers or symbols. And if you can please explain how it works.
To check if the person name contains only number. The code below has been tested and is working
<?php
error_reporting(0);
$number = '001222288';
if (!preg_match('/^[0-9]*$/', $number)) {
//error
echo 'Error does not contain only number';
} else {
echo 'success. it contains only number';
}
?>
if the variable number contains any other thing that is not number it result in error. eg
$number = 'ABFRT001222288';
To check for alphabets or string
<?php
error_reporting(0);
$string = 'ABTYUUU';
if (!preg_match('/^[A-Z]*$/', $string)) {
//error
echo 'Error does not contain only alphabet';
} else {
echo 'success. it contains only alphabets';
}
?>
Mark this as correct answer if it solve your problem
Thanks
The function preg_match use regex expressions. You can use an online tool for test your regex. I use debuggex, preg_match use PCRE expressions. In your case you should, you may use for numbers
preg_match("/[0-9]+/", $subject);
EDIT : We need more details for the symbols you want select
I have a validation that accepts phone numbers in a specific manner and dumps them in a database but it does not convert them the way I want.
For example, if I enter 9999999999 or 09999999999 or +919999999999 as a phone number, it gets into the database the way I have entered it.
How can I format it instead in the +919999999999 style irrespective of how the user has entered it?
function validate_phone($input){
$input = trim($input); //get rid of spaces at either end
if (preg_match('/^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$/',$input) == 1){
return $input;
}else{
return false;
}
}
The way I understand it, you only need the last 10 digits to which you prepend the +91 prefix.
We first make a small modification to the regex, adding parentheses around [789]\d{9} to capture it:
/^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?([789]\d{9})$/
Then we use the third parameter of preg_match to retrieve the capture, using the variable $m:
preg_match('/^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?([789]\d{9})$/', $input, $m)
The last 10 digits will be contained in $m[2], we then return that prefixed with +91:
function validate_phone($input){
$input = trim($input); //get rid of spaces at either end
if (preg_match('/^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?([789]\d{9})$/', $input, $m) == 1){
return '+91'.$m[2];
}else{
return false;
}
}
Test:
echo "\n".validate_phone('9999999999');
echo "\n".validate_phone('09999999999');
echo "\n".validate_phone('+919999999999');
Output:
+919999999999
+919999999999
+919999999999
I would like to figure out, how to check if the second to last character of a string is numeric.
My string is:
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
The URL is something like: http://www.domain.com/2/,http://www.domain.com/3/ and so on..
Is it possible to figure out if a number exists at the end of the URL before the last back slash / ?
Something like:
if (is_numeric($url, second-to-last-character)) {
// Do real stuff
} else {
// Do whatever
}
What about regexes ?
if (!preg_match('#/\d+/?$#', $url))
// There is no numeric at the end, abort !
I propose this because you won't know how many digits your id will have, so you can't just test the second-to-last character.
$fullurl = explode('/',$_SERVER['SCRIPT_NAME']);
$last = $fullurl[count($fullurl)-1];
//echo $last;
if(is_int($last))
echo "integer";
else
echo "Not integer";
You want to use substr. You can use this to get the second to last character.
http://php.net/manual/en/function.substr.php
is_numeric(substr($url, -2, 1);
if (is_numeric(substr($url, -2,1) ) {
should do you, You dont need the regex
use substr
if(is_numeric(substr($url,-2,1))){
//dosomething
}else{
echo "Invalid URL!";
}
in substr, the first parameter is the string, the second one is the offset, if the offset is negative, it will start at the end and go backwards, and the last one is the length. If not specified, it will go to the end of the string. So if you wanted to get the last tow characters, you would do substr($url,-2)
$url='http://www.domain.com/2/,http://www.domain.com/3/';
if(is_numeric (substr($url,-2,1))){
echo "This is number";
}else{
echo "This is not number";
}
I don't want to get offtopic, but when i'm dealing with URLs usually i delete ending slashes using
$url = rtrim($url, '/');
http://www.php.net/manual/en/function.rtrim.php
Usually you won't need that slash and it'll be messy when exploding the URL. You can use the substr() function as mentioned by previous answers to get the last character of the string then. AFAIK the substr() function is faster than using regular expressions for such a simple task.
if (is_numeric(substr($url, -1)) {}
edit
i just realized that if you are dealing with values > 9 you will be in trouble.
Better get the whole number as mentioned in another answer. If you prefer strange looking code with slightly better performance you can use that one instead of explode():
$value = strrev(strtok(strrev($url), '/'));
if (is_numeric($value)) {}
I know there are lots of tutorials and question on replacing something in a string.
But I can't find a single one on what I want to do!
Lets say I have a string like this
$string="Hi! [num:0]";
And an example array like this
$array=array();
$array[0]=array('name'=>"na");
$array[1]=array('name'=>"nam");
Now what I want is that PHP should first search for the pattern like [num:x] where x is a valid key from the array.
And then replace it with the matching key of the array. For example, the string given above should become: Hi! na
I was thinking of doing this way:
Search for the pattern.
If found, call a function which checks if the number is valid or not.
If valid, returns the name from the array of that key like 0 or 1 etc.
PHP replaces the value returned from the function in the string in place of the pattern.
But I can't find a way to execute the idea. How do I match that pattern and call the function for every match?
This is just the way that I am thinking to do. Any other method will also work.
If you have any doubts about my question, please ask in comments.
Try this
$string="Hi! [num:0]";
$array=array();
$array[0]=array('name'=>"na");
$array[1]=array('name'=>"nam");
echo preg_replace('#(\!)?\s+\[num:(\d+)\]#ie','isset($array[\2]) ? "\1 ".$array[\2]["name"] : " "',$string);
If you don't want the overhead of Regex, and your string format remains same; you could use:
<?php
$string="Hi! [num:0]";
echo_name($string); // Hi John
echo "<br />";
$string="Hello! [num:10]";
echo_name($string); // No names, only Hello
// Will echo Hi + Name
function echo_name($string){
$array=array();
$array[0]=array('name'=>"John");
$array[1]=array('name'=>"Doe");
$string = explode(" ", $string);
$string[1] = str_replace("[num:", "", $string[1]);
$string[1] = str_replace("]", "", $string[1]);
if(array_key_exists($string[1], $array)){
echo $string[0]." ".$array[$string[1]]["name"];
} else {
echo $string[0]." ";
}
}// function echo_sal ENDs
?>
Live: http://codepad.viper-7.com/qy2uwW
Assumptions:
$string always will have only one space, exactly before [num:X].
[num:X] is always in the same format.
Of course you could skip the str_replace lines if you could make your input to simple
Hi! 0 or Hello! 10
What would be the most efficient way to clean a user input that is a comma separated string made entirely on numbers - e.g
2,40,23,11,55
I use this function on a lot of my inputs
function clean($input){ $input=mysql_real_escape_string(htmlentities($input,ENT_QUOTES)); return $input; }
And on simple integers I do:
if (!filter_var($_POST['var'], FILTER_VALIDATE_INT)) {echo('error - bla bla'); exit;}
So should I explode it and then check every element of the array with the code above or maybe replace all occurrences of ',' with '' and then check the whole thing is a number? What do you guys think?
if (ctype_digit(str_replace(",", "", $input))) {
//all ok. very strict. input can only contain numbers and commas. not even spaces
} else {
//not ok
}
If it is CSV and if there might be spaces around the digits or commas and maybe even some quotation marks better use a regex to check if it matches
if (!preg_match('/\A\d+(,\d+)*\z/', $input)) die('bad input');
If you want to transform a comma-separated list instead of simply rejecting it if it's not formed correctly, you could do it with array_map() and avoid writing an explicit loop.
$sanitized_input = implode(",", array_map("intval", explode(",", $input)));
I would filter instead of error checking on simple input, though only 'cause I'm lazy, I suppose, and usually in a web context there's way too many cases to handle on what could be coming in that I wouldn't expect: Simple filter below.
<?php
$input = '234kljsalkdfj234a,a, asldkfja 345345sd,f jasld,f234l2342323##$##';
function clean($dirty){ // Essentially allows numbers and commas, just strips everything else.
return preg_replace('/[^0-9,]/', "", (string) $dirty);
}
$clean = clean($input);
echo $clean;
// Result: 234234,,345345,,2342342323
// Note how it doesn't deal with adjacent filtered-to-empty commas, though you could handle those in the explode. *shrugs*
?>
Here's the code and the output on codepad:
http://codepad.org/YfSenm9k