Search code examples
phpregexpreg-match

php preg_match multiple patterns conditionally


I have 2 serial number formats and if either of them match I want to redirect the page to the specified URL. Here's my code which has 2 regexes ORed followed by an ORed conditional statement that uses a group from the regexes:

$snregex = "/^(FL3)20([0-9]{2})([0-9]{2})([0-9]{5})$|^S[XNS][42][10][0]-([0-9]{2})([0-9]{2})([0-9]{2})-[0-9]{4}$/";
if (preg_match($snregex, $sn, $matches)) {
    $mm = $matches[1];
    $yr = $matches[2];
    $wk = $matches[3];

    # If SN MM codes are 25 or FL3 then use host server         
    if ($matches[1] == 'FL3' || $matches[1] == '25') {
        $url = "http://192.168.10.115/logs/20" . $yr . "/" . $wk . "/" . $sn . "/";

        # Redirect to host server
        redirect($url, '303');

The code only works for whatever regex I put in first in the preg_match conditional statement i.e. if the FL3 regex is first then I can successfully match the serial number but not the other. Likewise if I change that statement to have the '25' serial number first I can successfully match that serial number but not the other. Is there something wrong with the following:

$snregex = "/^(FL3)20([0-9]{2})([0-9]{2})([0-9]{5})$|^S[XNS][42][10][0]-([0-9]{2})([0-9]{2})([0-9]{2})-[0-9]{4}$/";

Example valid serial numbers are:

FL320150500022

SS210-251509-0098


Solution

  • You should var_dump($matches); then you'll see that ^(a)$|^(b)$ results in 2 groups, not 1 that contains either 'a' or 'b'. This means you should update your if-statement to something like if ($matches[1] == 'FL3' || $matches[5] == '25').

    Obviously I don't know the rest of your code; but I would not mix multiple regexps like this; instead I'd spit it into two separate if-statement:

    if (preg_match(FL...))
        $url = '...';
    elseif (preg_match(25))
        $url = '...';