Answer the question
In order to leave comments, you need to log in
How to check a string by mask?
Unfortunately, I practically do not know regular expressions and therefore the following question arose:
For example, there is a string: XXX-XXX-XXX
It is necessary to check the string and understand whether it matches the given mask.
You can write a regular expression that would check this case, but the fact is that masks can be dynamic and it should be possible for managers to set them, so to speak.
For example, the manager sets the following mask X-XX-XX-XXXXX and any combination of a string like:
7-Ds-re-SD434 fits this mask.
Of course, you can somehow nagovnocode, try to generate a regular expression, then substitute it, but you are interested in a beautiful and fast way. Maybe someone came across, share your experience.
Answer the question
In order to leave comments, you need to log in
Of course, you can somehow nagovnocode, try to generate a regular expression, then substitute it, but you are interested in a beautiful and fast way
$mask = 'X-XX-XX-XXXXX';
$test = '7-Ds-re-SD434';
$pattern = preg_replace_callback('/X+/', function ($m) {
return '[^-]{' . strlen($m[0]) . '}';
}, preg_quote($mask));
if (preg_match("/^{$pattern}$/", $test)) {
echo "Строка '$test' подходит под маску '$mask'";
}
$mask = 'X-XX-XX-XXXXX';
$test = '7-Ds-re-SD434';
if (preg_replace('/[^-]/', 'X', $test) == $mask) {
echo "Строка '$test' подходит под маску '$mask'";
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question