Regex to check a valid number in a format in PHP - php

I want to check if the string is in the following format
YYMMDD-XXXX
YYYYMMDD-XXXX
YYMMDDXXXX
YYYYMMDDXXXX
I have this regex
^\d{6,8}(-\d{4})?$
But then I am stuck. I am really new at regex. Can I get some help or some pointers?

Make the - optional and your regex works:
^\d{6,8}(-?\d{4})?$
https://regex101.com/r/uoF1HM/1/
This also would match many number formats though. Your example strings look like dates, if that is the case I'd use something stricter ( or already written e.g. https://stackoverflow.com/a/14566624/3783243 might be a good place to start).

You can use this function:
function checkFunc($value){
if (preg_match('/^[0-9]{6,8}(-?)[0-9]{4}$/', $value)) {
//is valid
return $value;
} else {
//is invalid
return false;
}
}
echo checkFunc("20180529-4444"); //20180529-4444
but for the first part of string, you will have to create different check for the date format

In your regex ^\d{6,8}(-\d{4})?$ youy have an optional group (-\d{4})? with a hyphen inside the group. That means that you can only match a format like \d{6,8} or with a hyphen \d{6,8}-\d{4} but not \d{6,8}\d{4} because the hyphen should be there according to the optional group.
If you want to match your values without any capturing groups you could make only the dash optional ?
That would match
^ Assert position at the start of the line
\d{6,8} Match 6 - 8 digits
-? Match optional dash
\d{4} Match 4 digits
$ Assert position at the end of the line
^\d{6,8}-?\d{4}$

Related

Unique regex for name validation

I want to check is the name valid with regex PHP, but i need a unique regex that allows:
Letters (upper and lowercase)
Spaces (max 2)
But there can't be a space after space..
For example:
Name -> Dennis Unge Shishic (valid)
Name -> Denis(space)(space) (not valid)
Hope you guys understand me, thank you :)
First, it's worth mentioning that having such restrictive rules for the names of persons is a very bad idea. However, if you must, a simple character class like this will limit you to just uppercase and lowercase English letters:
[A-Za-z]
To match one or more, you need to add a + after it. So, this will match the first part of the name:
[A-Za-z]+
To capture a second name, you just need to do the same thing preceded by a space, so something like this will capture two names:
[A-Za-z]+ [A-Za-z]+
To make the second name optional, you need to surround it by parentheses and add a ? after it, like this:
[A-Za-z]+( [A-Za-z]+)?
And to add a third name, you just need to do it again:
[A-Za-z]+( [A-Za-z]+)? [A-Za-z]+
Or, you could specify that the latter names can repeat between 1 and 2 times, like this:
[A-Za-z]+( [A-Za-z]+){1,2}
To make the resulting code easy to understand and maintain, you could use two Regex. One checking (by requiring it to be true) that only the allowed characters are used ^[a-zA-Z ]+$ and then another one, checking (by requiring it to be false) that there are no two (or more) adjacent spaces ( ){2,}
Try following working code:
Change input to whatever you want to test and see correct validation result printed
<?php
$input_line = "Abhishek Gupta";
preg_match("/[a-zA-Z ]+/", $input_line, $nameMatch);
preg_match("/\s{2,}/", $input_line, $multiSpace);
var_dump($nameMatch);
var_dump($multiSpace);
if(count($nameMatch)>0){
if(count($multiSpace)>0){
echo "Invalid Name Multispace";
}
else{
echo "Valid Name";
}
}
else{
echo "Invalid Name";
}
?>
A regex for one to three words consisting of only Unicode letters in PHP looks like
/^\p{L}+(?:\h\p{L}+){1,2}\z/u
Description:
^ - string start
\p{L}+ - one or more Unicode letters
(?:\h\p{L}+){1,2} - one or two sequences of a horizontal whitespace followed with one or more Unicode letters
\z - end of string, even disallowing trailing newline that a dollar anchor allows.

Get string between first and third occurence of character

I have many Strings looking like this:
QR-DF-6549-1 and QR-DF-6549
I want to get these parts of the strings:
DF-6549
Edit:
So I also want to get rid of the "-1" at the end, in case it exists.
How can I do this with php? I know substr but I am a bit lost at this one.
Thank you very much!
A regular expression is probably the best way given your sample data
// ^ start matching at start of string
// [A-Z]{2}- must start with two capital letters and a dash
// ( we want to capture everything that follows
// [A-Z]{2}- next part must start with two capital letters and a dash
// \d+ a sequence of one or more digits
// ) end the capture - this will be index 1 in the $match array allowed
if (preg_match('/^[A-Z]{2}-([A-Z]{2}-\d+)/', $str, $match)) {
$data=$match[1];
}

preg_match failing for me when checking different parts of the string

This preg_match will never work even though I think its the right thing.
I'm trying to check a string so that it's structured as follows
$value = US 01 02 1406034963 .JPG //I've put spaces in. The real one is below.
So:
The first part (US) is alphabets, only two characters from a-z
The second part (01) is a value 00 or 01
The third part (02) is digits 0-9 from 2 - 10 (can be 2 to 10 digits long)
The fourth part (1406034963) is a 10 digit figure, and only 10 digits
The fifth part is .jpg or .jpeg or .png. or .gif
But, my function always returns false. Can you please help?
//
function preset($value) {
if(preg_match('/^[a-z]{2}[00|01][0-9]{2,10}[0-9]{10}[.jpg|.jpeg|.png.|.gif]$/',$value)) {
return true;
} else {
return false;
}
}
$value = 'US01021406034963.JPG';
if(preset($value)) {
echo 'Yeah!';
} else {
echo 'Boo!';
}
[] denotes a character class. Simply put, a character class is a way of denoting a set of characters in such a way that one character of the set is matched.
You're trying to use alternation inside character classes. It will not work as you expect it to. For example, the regex [00|01] would match 0, the literal character |, or 1, and not 00 or 01.
To match either of the set, you can simply use grouping. In this case, you're not going to use the matched text anywhere, so you can use non-capturing groups. (?:00|01) is a non-capturing group that will match either 00 or 01. You can also shorten it and write just 0[01], but that totally depends on your taste.
And currently, your expression only matches lower-case strings. If you want it to work with upper-case, or even mixed-case strings, you can simply use the i modifier. It will make the pattern match the string case-insensitively.
You can simplify your function to just:
function preset($value) {
return (bool) preg_match('/^[a-z]{2}(?:00|01)[0-9]{2,10}[0-9]{10}\.(?:jpe?g|png|gif)$/i',$value);
}
Demo
You cannot place whole words inside of a character class, use a non-capturing group instead.
/^[a-z]{2}0[01][0-9]{2,10}[0-9]{10}\.(?:jpe?g|png|gif)$/i
You are erroneously using square (character class) instead of round (alternation) brackets in some places:
[00|01] should be (00|01).
[.jpg|.jpeg|.png.|.gif] should be \.(jpe?g|png|gif).

simple RegEx changes for phone number validation

i have this function to check my phone number:
function isValid( $what, $data ) {
switch( $what ) {
// validate a phone number
case 'phone_number':
$pattern = "/^[0-9-+]+$/";
break;
default:
return false;
break;
}
return preg_match($pattern, $data) ? true : false;
}
i want to change that regex to accept the following: the ) ( chars like (800) and the space.
So for example this number will pass the validation, right now is not passing:
+1 (201) 223-3213
Let us construct the regular expression step by step. Consider also that spaces are trimmed before matching.
at the beginning there might or might not be a + sign. This also needs to be escaped. \+?
then comes one or more digits, before the part with parenthesis [0-9]+ You might want to write [0-9]* if the number can begin directly with a group in parenthesis
then, optionally comes a group of digits in parenthesis: (\[0-9]+\)?. Suppose that only one such group is allowed
then comes the local phone number, hyphens also allowed: [0-9-]*
the final character must be a digit [0-9], hyphen is not allowed here
^\+?[0-9]+(\([0-9]+\))?[0-9-]*[0-9]$
See the result here. Trimming spaces looks like $trimmed = str_replace(' ', '', $pattern);.
How about this regexp:
/^[0-9-+()\s]+$/
See it in action here
'/\(?\b[0-9]{3}\)?[-. ]?[0-9]{3,5}[-. ]?[0-9]{4,8}\b/'
Since you seem to be using this for validation you can use str_replace('[\s\+\-\(\)]', '', $data) to get a string that should (if the phone number is valid) contain only digits. You can then test this assumption easily by running preg_match('\d{11}', $data) (the {11} means 11 digits, if there's a range allowed, use min, max like this {min,max}, e.g. \d{10,11}).
It's worth noting that this isn't as thorough as Lorlin's answer in that you're ignoring any invalid use of brackets, +s or -s. You may want to use a combination of the two, or whatever suits your needs the best.

PHP get if string is a time in the format 00:00

I have a string which may be a time or may be something else entirely. I want to find out if the string is in the format 00:00. I don't need to check whether the string is a valid time (ie not something like 25:98), just whether the string is in that format.
The regex would be /^\d{2}:\d{2}$/. Which matches a string if and only if it contains 2 digits before the colon and two digits after the colon.
Here is a PHP if/else condition with the above regex:
if (preg_match('/^\d{2}:\d{2}$/', $time)) {
// it is in the time format
} else {
// it is not in the time format
}
And regex for that would be ^[0-9]{2}:[0-9]{2}$
Try this
/\b\d{2}:\d{2}\b/
\b is a word boundary to ensure that there is nothing else before or ahead
\d is a digit, \d{2} means two digits.
if (preg_match('/^[0-9]{2,2}:[0-9]{2,2}$/', $string))
{
// ...
}

Categories