Search code examples
phparraysjsonregexpreg-match

A quicker PHP regex test


I need to sanitize incoming JSON that typically bears the form

'["P4950Zp550","P4950Zp575","P4950Zp600","P5000Zp550","P5000Zp575","P5000Zp600","P4975Zp550","P4975Zp600"]'

with the number of digits following each P|M, p|m varying between 3 and 5. json_decoding this and then applying the test

preg_match('/(P|M){1}[0-9]{3,5}Z(p|m){1}[0-9]{3,5}/',$value)

eight times, in a foreach loop, (I always have eight values in the array) would be a trivial matter. However, I am wondering if there might not be a Regex I could write that could do this in a oner without me having to first json_decode in the incoming string. My knowledge of RegExs is at its limits with the regex I have created here.


Solution

  • If you truly, deeply want to validate the 8-element array in a single pass while it is still a json string, you can use this:

    Pattern: ~^\["[PM]\d{3,5}Z[pm]\d{3,5}(?:","[PM]\d{3,5}Z[pm]\d{3,5}){7}"]$~

    Pattern Demo -- this matches the first, then the seven to follow; all wrapped appropriately.

    Code (Demo)

    $string = '["P4950Zp550","P4950Zp575","P4950Zp600","P5000Zp550","P5000Zp575","P5000Zp600","P4975Zp550","P4975Zp600"]';
    
    if (preg_match('~^\["[PM]\d{3,5}Z[pm]\d{3,5}(?:","[PM]\d{3,5}Z[pm]\d{3,5}){7}"]$~', $string)) {
        echo "pass";
    } else {
        echo "fail";
    }
    // outputs: pass
    

    Sometimes, you just want to bulk validate input :]