N
N
nepster-web2015-09-21 22:28:09
PHP
nepster-web, 2015-09-21 22:28:09

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

2 answer(s)
C
Cat Anton, 2015-09-21
@27cm

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

Or you can not nagovnokodit, but beautifully and quickly generate a regular expression from a mask.
ideone.com/YY4Yhh
$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'"; 
}

But there is an easier option:
ideone.com/GiwMAY
$mask = 'X-XX-XX-XXXXX';
$test = '7-Ds-re-SD434';

if (preg_replace('/[^-]/', 'X', $test) == $mask) {
    echo "Строка '$test' подходит под маску '$mask'"; 
}

S
Sergey N, 2015-09-22
@Albibek

You can do without regulars. You have a clear separator - a dash. Do a split by "-" for the mask and the string itself. Then it is enough to compare the lengths of the arrays and element by element the lengths of the resulting strings.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question