Psyche
Psyche

Reputation: 8773

Extract certain values from a string

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.

Upvotes: 1

Views: 108

Answers (4)

Niels
Niels

Reputation: 49919

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
)

Upvotes: 0

abcde123483
abcde123483

Reputation: 3905

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

?>

Upvotes: 0

Shomz
Shomz

Reputation: 37701

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+/.

Upvotes: 0

FailedDev
FailedDev

Reputation: 26930

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

Upvotes: 2

Related Questions