justinhilles
justinhilles

Reputation: 1

Parse out measurements (L x W x H) in string

I need to regex a string in PHP with preg_match_all to find parts and populate a database. I have most of it worked out but the only part that Im hung up on is finding the measurements portion:

Here is my string:

"NA153 - Fire Bowl Fabricated From a Vintage Propane Tank, Would Work as A Water Feature or a Glass Top Could be Added for an Unusual Coffee Table as Well, 23H x 39W - $1200.00"

Here is My reg ex so far:

"%([A-Z0-9]{5}) #Find Sku
\s*\-?\s*
(.*)\s*\, # Find Title
\s*
.*([0-9][HWD])\s*\-? #Find Dimensions
\s*
\$([0-9\.]*) # Find Price
%x"

It finds sku, title, and price correctly. But dimensions it is returning only 1 "9W"

here is my function call:

preg_match_all('{{regular expression}}', '{{string}}', $arr, PREG_PATTERN_ORDER);

Any help or insight would be greatly appreciated as I am new to regular expressions.

Upvotes: 0

Views: 364

Answers (2)

Toto
Toto

Reputation: 91498

If dimensions can be decimals, you could use:

(\d+(?:\.\d+)+[HWD](?:\s+x\s+\d+(?:\.\d+)+[HWD])*)\s*-? #Find Dimensions

Upvotes: 0

ean5533
ean5533

Reputation: 8994

Just throw a + quantifier after the [0-9] group for dimensions, like so:

"%([A-Z0-9]{5}) #Find Sku
\s*\-?\s*
(.*)\s*\, # Find Title
\s*
.*([0-9]+[HWD])\s*\-? #Find Dimensions
\s*
\$([0-9\.]*) # Find Price
%x"

That + quantifier will cause it to greedily find as many numbers as it can before continuing to the [HWD].

Edit: Sorry, that will only get you `39W'. To make it grab more than one dimension, you need to change it further:

'/([A-Z0-9]{5}) #Find Sku
\s*\-?\s*
(.*)\s*\, # Find Title
\s*
.*?([0-9]+[HWD](?:\s+x\s+[0-9]+[HWD])*)\s*\-? #Find Dimensions
\s*
\$([0-9\.]*) # Find Price
%/'

Upvotes: 1

Related Questions