1

I have a string like this:

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

How can I extract only the numeric pairs from it ("1,1", "2,3" and "3,5") and put them in an array?

I know I can use explode() multiple times, but I was wondering if there's an easy way using regex.

I'm using PHP.

1
  • i know this is tagged "regex" but what about using explode ? Commented Nov 20, 2011 at 18:23

4 Answers 4

2

This :

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

should get all your number in the $result array.

Why:

"
(?<=    # 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)
"
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! It's ok but without the second line.
@Psyche Yeah, that's just an assignment.
0

Well this /\d,\d/ should match all the single-digit number pairs, use it with with preg_match_all to get an array of strings num,num. If you expect multi-digit numbers, use /\d+,\d+/.

Comments

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);

?>

Comments

0

You can try this:

http://codepad.org/jtWs6DjM

But it returns also the strings before:

<?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);

?>

Result:

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

2 Comments

Thanks, but I want only the numeric pairs.
Updated so it only returns numbers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.