Rachie
Rachie

Reputation: 443

php preg_match partial matching

I'm trying to parse a string into components. My solution works for full strings, but I want to be able to account for strings with potentially fewer components. For instance, I want to be able to match G02F 1/1335, G02F 1, G02F, etc. With preg_match, if not all the capturing groups match, the entire output is invalid.

$string = 'G02F   1/1335';
$string = strtoupper(preg_replace('/\s+/', '', $string));
preg_match('%^([A-H])([0-9]{1,2})([A-Z])([0-9]{1,4})/([0-9]{1,6})$%', $string, $parsed);

Upvotes: 0

Views: 270

Answers (1)

Danijel
Danijel

Reputation: 12689

As @mario suggested in comment, make subpatterns optional with ?:

preg_match( '%^([A-H])(\d{1,2})([A-Z])\s*(\d{1,4})?/?(\d{1,6})?$%', $string, $parsed );

Upvotes: 1

Related Questions