简体   繁体   English

使用正则表达式从字符串中提取两个值

[英]Extract two values from string using regex

I have a string that looks like this: 我有一个看起来像这样的字符串:

'p10005c4' 'p10005c4'

I need to extract the productId 10005 and the colorId 4 from that string into these variables: 我需要从该字符串中提取productId 10005和colorId 4到以下变量中:

$productId $colorId $ productId $ colorId

productId is > 10000. colorId > 1. productId>10000。colorId> 1。

How can I do this clean and nice using regex? 我如何使用正则表达式来做到这一点呢?

如果您的字符串始终是pXXXcXX ,我建议您放弃正则表达式,而只使用几个字符串函数。

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

You can use the following regex: 您可以使用以下正则表达式:

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

If you want to make sure the product code is 5 digits: 如果要确保产品代码为5位数字:

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

This should be possible with the following regex: 使用以下正则表达式应该可以实现:

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

This basically means, match any string that consists of ap, followed by one or more digits, then followed by ac, then followed by one or more digits. 这基本上意味着匹配由ap,后跟一个或多个数字,然后是ac,然后是一个或多个数字的任何字符串。 The parentheses indicate capture groups, and since you want to capture the two ids, they're surrounded by them. 括号表示捕获组,并且由于您要捕获两个id,因此它们被它们包围。

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 . 有关正则表达式入门的更多信息,您可能需要查看Regular-Expressions.info

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM