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. :)
Related
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}$
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";
}
I'm trying to check if a username string is all numbers (but the field is not a numeric field). If so, I need the string to be 5 characters in length by adding leading 0's.
I have this code:
<?php
$getuname = $_GET['un'];
if (mb_strlen($getuname) <= 1){
$getuname = "0".$getuname;
}
if (mb_strlen($getuname) <= 2){
$getuname = "0".$getuname;
}
if (mb_strlen($getuname) <= 3){
$getuname = "0".$getuname;
}
if (mb_strlen($getuname) <= 4){
$getuname = "0".$getuname;
}
echo $getuname;
?>
The above code works for making sure the string is 5 characters by adding zeros, but it's not very pretty and I'm sure there is a much nicer way to do it. Anyone?
Also, this whole piece needs to be wrapped in an IF statement that is checking to see if it contains nothing but numbers in the first place. I tried using !is_numeric, but this doesn't seem to work. I'm assuming because it's not a numeric type field.
You can use is_numeric to check for a numeric field, it doesn't matter whether the variable is a string or not. See example here.
Then you can simply pad using str_pad()
if(!is_numeric($test))
echo $test . ' is not a number!';
else
echo str_pad($test, 5, 0, STR_PAD_LEFT);
Edit: as flixer pointed out, is_numeric() won't actually do what you specifically asked (to check that a string contains only digits, i.e. no periods, commas, dashes etc which would be considered to "be a number"). In this case, use ctype_digit() instead:
$test_number = '123.4';
$test_number2 = '12345';
echo ctype_digit($test_number) ? $test_number . ' is only digits' : $test_number . ' is not only digits';
echo ctype_digit($test_number2) ? $test_number2 . ' is only digits' : $test_number2 . ' is not only digits';
// output:
// 123.4 is not only digits
// 12345 is only digits
The key here is to avoid regex when you have better tools to do the job.
To add a little to this, ctype_digit() might return false when you pass in an integer variable: (example from PHP manual)
ctype_digit( '42' ); // true
ctype_digit( 42 ); // false - ASCII 42 is the * symbol
This can be OK, depending on the situation you're using this in. In your case you're validating a $_GET variable, which is always going to be a string so it won't affect you.
Docs:
str_pad(): http://php.net/str_pad
ctype_digit(): http://www.php.net/manual/en/function.ctype-digit.php
OP Here, this is it all together. Works like a charm...
if (ctype_digit($getuname) == true) {
$getuname = str_pad($getuname, 5, 0, STR_PAD_LEFT);
}
Use the str_pad() function. Like this:
$getuname = str_pad($_GET['un'], 5, '0', STR_PAD_LEFT);
Try this:
<?php
$getuname = $_GET['un'];
if(ctype_digit($getuname))
$getuname = str_repeat("0", 5-strlen($getuname)) . $getuname;
?>
Hope it works for u.
This should be a clean solution:
$getuname = $_GET['un'];
if(preg_match('/^\d+$/',$getuname)){
echo sprintf('%05d', $getuname);
}else{
// incorrect format
}
<?php
$getuname = $_GET['un'];
while (strlen($getuname) < 5) {
$getuname = '0' . $getuname;
}
echo $getuname;
?>
This is a tricky one: I want to add +1 to this number: 012345675901 and the expected result is: 012345675902. Instead I get: 2739134 when I do this:
echo (012345675901+1);
When I try:
echo ('012345675901'+1);
I get this: 12345675902 which is pretty close to what I need, but it removes the leading zero.
When I do this:
echo (int) 012345675901;
I get 2739133. I also tried bcadd() without success:
echo bcadd(012345675901, 1);
which resulted in 2739134.
I know I am missing something here. I would really appreciate your help!
UPDATE 1
Answer 1 says that the number is octal:
function is_octal($x) {
return decoct(octdec($x)) == $x;
}
$number = is_octal(012345675901);
echo var_dump($number);
The above returns false. I thought I needed to convert this from octal to a normal string but didn't work. I can't avoid not using the above number - I just need to increment it by one.
EDIT 2
This is the correct code:
$str = '012345675901';
$str1 = ltrim($str, '0'); // to remove the leading zero
$str2 = bcadd($str1, 1); // +1 to your result
$str3 = strlen($str); // get the length of your first number
echo str_pad($str2, $str3, '0', STR_PAD_LEFT); // apply zeros
Thank you everyone for your help! The above code produces: 012345675902 as expected
The leading 0 is treating your number as octal.
The leading 0 you need for output as a string, is a purely a representation.
please see the code for explanation.
$str = "012345675901"; // your number
$str1 = ltrim($str, '0'); // to remove the leading zero
$str2 = bcadd($str1, 1); // +1 to your result
$str3 = strlen($str); // get the length of your first number
echo str_pad($str2, $str3, '0', STR_PAD_LEFT); // apply zeros
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
}