tags:

views:

137

answers:

3

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?

+2  A: 

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+)/'
Gavin Miller
+2  A: 

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);
zombat
I want to learn reg exp! That is so ugly
Regular expressions are much slower than string functions, and should be avoided when they aren't necessary. They are much harder to debug as well.
zombat
Regular expressions are not always the best answer to a given problem. They can also make the code more difficult to understand if the developer isn't well versed in them.
Doomspork
"They are much harder to debug as well." -- this is not always true, it depends on the use to which they are put. For instance, I'd personally consider the regex in the accepted answer to be more "readable" as far as determining function than the string functions version.
Amber
@Dav how does one step into a regular expression to debug?
Doomspork
+2  A: 

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.

Sebastian P.