Marcus Roman
Marcus Roman

Reputation:

Extract two values from string using regex

I have a string that looks like this:

'p10005c4'

I need to extract the productId 10005 and the colorId 4 from that string into these variables:

$productId $colorId

productId is > 10000. colorId > 1.

How can I do this clean and nice using regex?

Upvotes: 0

Views: 1271

Answers (3)

This should be possible with the following regex:

/p(\d+)c(\d+)/

This basically means, match any string that consists of a p, followed by one or more digits, then followed by a c, then followed by one or more digits. The parentheses indicate capture groups, and since you want to capture the two ids, they're surrounded by them.

To use this for your purposes, you'd do something like the following:

$str = 'p10005c4';
$matches = array();

preg_match('/p(\d+)c(\d+)/', $str, $matches);

$productId = $matches[1];
$colorId   = $matches[2];

For more information on getting started with regular expressions, you might want to take a look at Regular-Expressions.info.

Upvotes: 2

zombat
zombat

Reputation: 94147

If your string is always pXXXcXX, I would suggest you forego the regular expressions, and just use a couple of string functions.

list($productId,$colorId) = explode('c',substr($string,1),2);

Upvotes: 3

Gavin Miller
Gavin Miller

Reputation: 43815

You can use the following regex:

'/p(\d+)c(\d+)/'

If you want to make sure the product code is 5 digits:

'/p(\d{5})c(\d+)/'

Upvotes: 2

Related Questions