PHP - Why is my preg_match not working? - php

I'm trying to make sure that when the user registers they use a specific series of characters. In my case i want them to enter something like "d1111111" so I want it to be 8 characters in total and to start with the letter d lowercase or uppercase, to allow the other 7 characters to be a number between 0 and 9. All help appreciated, thanks.
here's my code so far
$regex = '/[d][0-9]{8}/';
if(preg_match($regex, $username)){
echo "Valid";
} else {
echo "not a valid username";
}

Use for example
$regex = '/^[dD][0-9]{7}$/';
or
$regex = '/^d\d{7}$/i';
A character class […] matches a single character, [dD] therefore matches the letter d or D.
Alternatively, you can use the i option (also referred to as modifier) at the end of the expression, to let your regular expression match case-insensitively. It is also possible to change the mode inside the expression, I personally have never used that, though.
\d matches any digit and is the same as [0-9]. {7} denotes how many digits to match.
You need ^ and $ to ensure that the regular expression matches the whole username.
For PHP in particular, see PHP's PCRE docs.

Your regex is wrong here. First, there's no need of a character class to capture d. Just a literal d along with start-of-the-string anchor ^.
Now we want the remaining 7 letters to be digits. So it would be following with the end-of-the-string anchor $
$regex = '/^d\d{7}$/'

Related

preg_match for string not work

i have string like p88t9014-name here is p is for Product and t for sub product id
and after - the name is user defined any name.
i try to match string with preg_match with this code ::
$name="p88t0056-name";
if(preg_match('/p[0-9]t[0-9]-[A-Z,a-z]/',$name,$match)) {
echo "yes";
} else {
echo "No";
}
print_r($m);
i just try to match formate if is this with format p[number]t[number]-[anystring]. but my code is not working.
You need to put quantifiers after your character classes:
'/p[0-9]+t[0-9]+-[A-Za-z]+/'
This regex will work for you:
/p(\d+)t(\d+)-(\w+)/g
Demo
Explaination:
p matches letter p
\d+ matches numbers 0-9
t matches letter t
\d+ matches numbers 0-9
- matches dash '-'
\W+ match any word character [a-zA-Z0-9_]
and g to catch all matches.
I am also not an expert on regex but trying multiple options on http://www.regex101.com helps as it shows explanations of characters in right side panel. Hope it helps in future :)
If you're always going to have a set number of digits, you can also use:
/^p[0-9]{2}t[0-9]{4}-[A-Za-z]+$/
Here's an example on RegExr: http://www.regexr.com/390ds
in regex [0-9] matches exactly one character, and so does [A-Z,a-z], and therefore $name is not match the pattern you give. Strings like "p8t0-A" and "p0t2," pass the test.
Besides, another problem in your pattern is that: [A-Z,a-z] matches not only alphabets but also , (a single comma). I guess the pattern you need is p[0-9]+t[0-9]+-[A-Za-z]+, in which +s represent "occurs at least once".

check the value entered by the user with regular expression in php

in my program php, I want the user doesn't enter any caracters except the alphabets
like that : "dgdh", "sgfdgdfg" but he doesn't enter the numbers or anything else like "7657" or "gfd(-" or "fd54"
I tested this function but it doesn't cover all cases :
preg_match("#[^0-9]#",$_POST['chaine'])
how can I achieve that, thank you in advance
The simplest can be
preg_match('/^[a-z]+$/i', $_POST['chaine'])
the i modifier is for case-insensitive. The + is so that at least one alphabet is entered. You can change it to * if you want to allow empty string. The anchor ^ and $ enforce that the whole string is nothing but the alphabets. (they represent the beginning of the string and the end of the string, respectively).
If you want to allow whitespace, you can use:
Whitespace only at the beginning or end of string:
preg_match('/^\s*[a-z]+\s*$/i', $_POST['chaine'])
Any where:
preg_match('/^[a-z][\sa-z]*$/i', $_POST['chaine']) // at least one alphabet
Only the space character is allowed but not other whitespace:
preg_match('/^[a-z][ a-z]*$/i', $_POST['chaine'])
Two things. Firstly, you match non-digit characters. That is obviously not the same as letter characters. So you could simply use [a-zA-Z] or [a-z] and the case-insensitive modifier instead.
Secondly you only try to find one of those characters. You don't assert that the whole string is composed of these. So use this instead:
preg_match("#^[a-z]*$#i",$_POST['chaine'])
Only match letters (no whitespace):
preg_match("#^[a-zA-Z]+$#",$_POST['chaine'])
Explanation:
^ # matches the start of the line
[a-zA-Z] # matches any letter (upper or lowercase)
+ # means the previous pattern must match at least once
$ # matches the end of the line
With whitespace:
preg_match("#^[a-zA-Z ]+$#",$_POST['chaine'])

php regular expression for 4 characters

I am trying to construct a regular expression for a string which can have 0 upto 4 characters. The characters can only be 0 to 9 or a to z or A to Z.
I have the following expression, it works but I dont know how to set it so that only maximum of 4 characters are accepted. In this expression, 0 to infinity characters that match the pattern are accepted.
'([0-9a-zA-Z\s]*)'
You can use {0,4} instead of the * which will allow zero to four instances of the preceding token:
'([0-9a-zA-Z\s]{0,4})'
(* is actually the same as {0,}, i.e. at least zero and unbounded.)
If you want to match a string that consists entirely of zero to four of those characters, you need to anchor the regex at both ends:
'(^[0-9a-zA-Z]{0,4}$)'
I took the liberty of removing the \s because it doesn't fit your problem description. Also, I don't know if you're aware of this, but those parentheses do not form a group, capturing or otherwise. They're not even part of the regex; PHP is using them as regex delimiters. Your regex is equivalent to:
'/^[0-9a-zA-Z]{0,4}$/'
If you really want to capture the whole match in group #1, you should add parentheses inside the delimiters:
'/(^[0-9a-zA-Z]{0,4}$)/'
... but I don't see why you would want to; the whole match is always captured in group #0 automatically.
You can use { } to specify finite quantifiers:
[0-9a-zA-Z\s]{0,4}
http://www.regular-expressions.info/reference.html
You can avoid regular expressions completely.
if (strlen($str) <= 4 && ctype_alnum($str)) {
// contains 0-4 characters, that are either letters or digits
}
ctype_alnum()

Regex Rules for First and Second Character

I need help on following regular expression rules of javascript and php.
JS
var charFilter = new RegExp("^[A|B].+[^0123456789]$");
PHP
if (!preg_match('/^[A|B].+[^0123456789]$/', $data_array['sample_textfield'])) {
This regular expression is about
First character must be start with A or B and last character must not include 0 to 9.
I have another validation about, character must be min 3 character and max 6 number.
New rule I want to add is, second character cannot be C, if first letter is A.
Which means
ADA (is valid)
ACA (is not valid)
So I changed the regex code like this
JS
var charFilter = new RegExp("^(A[^C])|(B).+[^0123456789]$");
PHP
if (!preg_match('/^(A[^C])|(B).+[^0123456789]$/', $data_array['sample_textfield'])) {
It is worked for first and second character. If i type
ACA (it says invalid) , But if i type
AD3 (it says valid), it doesn't check the last character anymore. Last character must not contain 0 to 9 number, but it's show as valid.
Can anyone help me to fix that regex code for me ? Thank you so much.
Putting all of your requirements together, it seems that you want this pattern:
^(?=.{3,6}$)(?=A(?!C)|B).+\D$
That is:
From the beginning of the string ^
We can assert that there are between 3 to 6 of "any" characters to end of the string (?=.{3,6}$)
We can also assert that it starts with A not followed by C, or starts with B (?=A(?!C)|B)
And the whole thing doesn't end with a digit .+\D$
This will match (as seen on rubular.com):
= match = = no match =
ADA ACA
ABCD AD3
ABCDE ABCDEFG
ABCDEF
A123X
A X
Note that spaces are allowed by .+ and \D. If you insist on no spaces, you can use e.g. (?=\S{3,6}$) in the first part of the pattern.
(?=…) is positive lookahead; it asserts that a given pattern can be matched. (?!…) is negative lookahead; it asserts that a given pattern can NOT be matched.
References
regular-expressions.info
Lookarounds, Alternation, Anchors, Repetition, Dot, Character Class
Related questions
How does the regular expression (?<=#)[^#]+(?=#) work?
On alternation precedence
The problem with the original pattern is in misunderstanding the precedence of the alternation | specifier.
Consider the following pattern:
this|that-thing
This pattern consists of two alternates, one that matches "this", and another that matches "that-thing". Contrast this with the following pattern:
(this|that)-thing
Now this pattern matches "this-thing" or "that-thing", thanks to the grouping (…). Coincidentally it also creates a capturing group (which will capture either "this" or "that"). If you don't need the capturing feature, but you need the grouping aspect, use a non-capturing group ``(?:…)`.
Another example of where grouping is desired is with repetition: ha{3} matches "haaa", but (ha){3} matches "hahaha".
References
regular-expressions.info/Brackets for Grouping
Your OR is against the wrong grouping. Try:
^((A[^C])|(B)).+[^0123456789]$
In jasonbars solution the reason it doesn't match ABC is because it requires A followed by not C, which is two characters, followed by one or more of any character followed by a non number. Thus if the string begins with an A the minimum length is 4. You can solve this by using a look ahead assertion.
PHP
$pattern = '#^(A(?=[^C])|B).+\D$#';
i think it should be like
/^(A[^C]|B.).*[^0-9]$/
try this test code
$test = "
A
B
AB
AC
AAA
ABA
ACA
AA9
add more
";
$pat = '/^(A[^C]|B.).*[^0-9]$/';
foreach(preg_split('~\s+~', $test) as $p)
printf("%5s : %s\n<br>", $p, preg_match($pat, $p) ? "ok" : "not ok");

preg_match in php

I want to use preg_match() such that there should not be special characters such as ``##$%^&/ '` in a given string.
For example :
Coding : Outputs valid
: Outputs Invalid(String beginning with space)
Project management :Outputs valid (space between two words are valid)
'Design23' :Outputs valid
23Designing : outputs invalid
123 :Outputs invalid
I tried but could not reach to a valid answer.
Does a regex like this help?
^[a-zA-Z0-9]\w*$
It means:
^ = this pattern must start from the beginning of the string
[a-zA-Z0-9] = this char can be any letter (a-z and A-Z) or digit (0-9, also see \d)
\w = A word character. This includes letters, numbers and white-space (not new-lines by default)
* = Repeat thing 0 or more times
$ = this pattern must finish at the end of the string
To satisfy the condition I missed, try this
^[a-zA-Z0-9]*\w*[a-zA-Z]+\w*$
The extra stuff I added lets it have a digit for the first character, but it must always contain a letter because of the [a-zA-Z]+ since + means 1 or more.
Try
'/^[a-zA-Z][\w ]+$/'
If this is homework, you maybe should just learn regular expressions:
Regular expressions tutorial
Regular expressions reference
PCRE syntax reference for PHP

Categories