从字符串中提取某些值

时间:2011-11-20 18:06:40

标签: php regex string

我有一个这样的字符串:

filter-sex=1,1_filter-size=2,3_filter-material=3,5

如何只从中提取数字对(“1,1”,“2,3”和“3,5”)并将它们放在一个数组中?

我知道我可以多次使用explode(),但我想知道是否有一种使用正则表达式的简单方法。

我正在使用PHP。

4 个答案:

答案 0 :(得分:2)

这:

preg_match_all('/(?<==)\d+,\d+/', $subject, $result, PREG_PATTERN_ORDER);
$result = $result[0];

应该在$ result数组中获取所有数字。

<强>为什么:

"
(?<=    # Assert that the regex below can be matched, with the match ending at this position (positive lookbehind)
   =       # Match the character “=” literally
)
\d      # Match a single digit 0..9
   +       # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
,       # Match the character “,” literally
\d      # Match a single digit 0..9
   +       # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
"

答案 1 :(得分:0)

这个/\d,\d/应与所有单位数字对匹配,并与preg_match_all一起使用以获取字符串数组num,num。如果您希望使用多位数字,请使用/\d+,\d+/

答案 2 :(得分:0)

你可以试试这个:

http://codepad.org/jtWs6DjM

但它之前还返回字符串:

<?php
$string = "filter-sex=1,1_filter-size=2,3_filter-material=3,5";

$result = preg_split('/[a-z-_]+=([0-9],[0-9])/', $string, null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

print_r($result);

?>

结果:

Array
(
    [0] => 1,1
    [1] => 2,3
    [2] => 3,5
)

答案 3 :(得分:0)

<?php
$str = "filter-sex=1,1_filter-size=2,3_filter-material=3,5";

preg_match_all("#[0-9]+,[0-9]+#", $str, $res);    
print_r($res);

?>