Search code examples
phpregexpreg-match

preg_match on formula and characters given?


I need to be able to tell if there is a match of serials given the following:

$formula = 'XXXXX-XXXXX-XXXXX-XXXXX-XXXXX';
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$serials = array(
    '9876-345-ABC',
    '7856Y-YURYW-00UEW-YUI23-YYYYY',
    '0934Y-R6834-27495-89999-11123'
);

So, given the following $serials array, how to return true for all values matching any of the characters in $chars using the specified formula, where X is a placeholder for any character inside of $chars. But I also need to make sure the hyphens in the formula are in the right place in the value of the serials given.

foreach($serials as $serial)
{
    if(preg_match("???", $serial) === 0)
        echo 'found';
}

Should echo found on the last 2 elements of $serials. Seems simple enough, but I still can't wrap my head around regexes no matter how hard I try.


Solution

  • $formula = 'XXXXX-XXXXX-XXXXX-XXXXX-XXXXX';
    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    
    $serials = array(
        '9876-345-ABC',
        '7856Y-YURYW-00UEW-YUI23-YYYYY',
        '0934Y-R6834-27495-89999-11123'
    );
    
    foreach($serials as $serial) {
        $str  = str_replace(str_split($chars), 'X', $serial);
        echo $str == $formula ? "yes" : "no";
    }