0

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

4
  • Show us the string that you are checking against. Commented Jun 30, 2015 at 16:00
  • Try grouping the ors something like /^(?:(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})$/ Without samples can't test further. Commented Jun 30, 2015 at 16:00
  • You may write two different preg_match tests (opposed to your complex combined one), one for each regexp, then your pb become a simple php OR test. It also should be a lot easier to read and maintain... Commented Jun 30, 2015 at 16:03
  • Since your patterns are totally unclear, could you show for the two example strings where are the year, the month, and the week? Commented Jun 30, 2015 at 16:59

1 Answer 1

1

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 = '...';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.