I want a regex for an text, that allow it, if atleast 1 word with 2 letters are inside, and minimum 25 letters or digits and also allow (0-9äöü,.' -), if other letters or digits there, it should be give an error.
Example:
correct:
false:
Regex:
if(preg_match("/([A-Za-z]{2})\w+/",$text)){
if(!preg_match("/[a-zäöüA-ZÄÖÜ,.' -]/g",$text)){echo 'error';}
else{echo'error';}
I'm not sure how to get the solution in code.
How do you match letters in regex? To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" .
The backslash character (\) in a regular expression indicates that the character that follows it either is a special character (as shown in the following table), or should be interpreted literally. For more information, see Character Escapes. Escaped character. Description. Pattern.
To represent this, we use a similar expression that excludes specific characters using the square brackets and the ^ (hat). For example, the pattern [^abc] will match any single character except for the letters a, b, or c.
What you might do is use a positive lookahead to assert the length of 25 - 999 and also assert that there are 2 consecutive [a-z]
Then match your character class [a-zA-Z0-9äöü,.' -]+
with the allowed items adding a-z and A-Z to it.
^(?=.{25,999})(?=.*[a-z]{2})[a-zA-Z0-9äöü,.' -]+$
^
Start of string(?=.{25,999})
Positive lookahead, assert 25 - 99 characters(?=.*[a-z]{2})
Positive lookahead, assert 2 times [a-z][a-zA-Z0-9äöü,.' -]+
Match any of the listed 1+ times$
End of stringRegex demo | Php demo
For example (I have made the strings longer to account for the minimum length of 25)
$strings = [
"This is a text with John Doe",
"This is a text with Max Müstermann ",
"This is a text withJohn-Frank' Doe.",
"This is a text with John/Doejlkjkjlk",
];
$pattern = "/^(?=.{25,999})(?=.*[a-z]{2})[a-zA-Z0-9äöü,.' -]+$/";
foreach ($strings as $string) {
if (preg_match($pattern, $string)) {
echo "Ok ==> $string" . PHP_EOL;
} else {
echo "error" . PHP_EOL;
}
}
Result
Ok ==> This is a text with John Doe
Ok ==> This is a text with Max Müstermann
Ok ==> This is a text withJohn-Frank' Doe.
error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With