There are names of records in which are mixed several types of SKU that may contains symbols, digits, etc.
Examples:
Name of product 67304-4200-52-21
67304-4200-52 Name of product
67304-4200 Name of product
38927/6437 Name of product
BKK1MBM06-02 Name of product
BKK1MBM06 Name of product
I need to preg_match (PHP) only SKU part with any symbols in any combinations.
So i wrote pattern:
/d+/d+|d+-?d+-?d+-?d+|bbkk.*b/i
It works but not with [BKK*] SKU.
Is it way to combine all this types of SKU together in one pattern?
2
Answers
Use
See regex proof.
REGEX101 EXPLANATION
The pattern
d+-?d+-?d+-?d+
means that there should be at least 4 digits as all the hyphens are optional, but in the example data the part with the numbers have at least a single hyphen, and consist of 2, 3 or 4 parts.You could repeat the part with the digits and hyphen 1 or more times, and instead of using
.*b
useS*b
to match optional non whitespace chars that will backtrack until the last word boundary.Note that if you use another delimiter in php than
/
, you don’t have to escape/
Using a case insensitive match:
Explanation
b
A word boundary to prevent a partial word match(?:
Non capture group for the alternativesd+(?:-d+)+
Match 1+ digits and repeat 1 or more times matching-
and again 1+ digits (or use{1,3}
instead of+
)|
OrbkkS*
Matchbkk
and optional non whitespace characters|
Ord+/d+
Match 1+ digits/
and 1+ digits)
Close the non capture groupb
A word boundarySee a regex101 demo.