Bolek Lolek Bolek Lolek - 7 months ago 24
PHP Question

My pattern in preg_match not working as i want

I want to get:

  • false for A3312+A192389+B2323+B948348

  • false for A6712+A1922389

  • false for A4512

  • true for A4552+B948348
    (only one Aelement and one or more Belement)

I tried:

print_r(preg_match('/^A((?!\+A).)\+B(.*)$/', $string));


So it looks as if the basic pattern you're after is "A(digits)+B(digits)"

Your expression seems a bit over-complicated for that purpose, I'd simply use:

preg_match('/^A\d+(\+B\d+)+$/', $input, $match);

If the input can be alphanumeric (A(alnum)+B(alnum), just use

preg_match('/^A[:alnum:]+(\+B[:alnum:]+)+$/', $input, $match);


Basically, the 2 absolute hard requirements are: the input string should start with an upper-case A, and there should be one + sign, followed by an upper-case B. Whatever the characters in between should be, you just have to add a character group that best fits your requirements. From the examples you gave \d+ (one or more digits) seems to fit the bill. If "A00FF33+B123ABC" should be valid, I'd either use [:alnum:] or [0-9A-F] (for hex values) instead.

The trick for the one-or-more requirement is to create a group for the +Belement part of the match, and repeat that group one or more times:

\+B\d+ //matches once
(\+B\d+)+ //matches once or more