zambliner
zambliner

Reputation: 466

How to get the numbers with sign from a string using regex in php

I have the example array of strings like below.

$arrayOfString = array(
   [0]=>'customer service[-3] technical support[-3]',
   [1]=>'picture quality[+2]feature[+2]',
   [2]=>'smell[-2]',
   [3]=>'player[+2]',
   [4]=>'player[-3][u]',
   [5]=>'dvd player[-2]',
   [6]=>'player[+2][p]',
   [7]=>'format[+2][u]progressive scan[-2]'
);

I wanted to extract the each word and the associated numeric value inside '[' & ']' (only the numbers not the string inside those braces but including the polarity sign ). So the output array must look something like this:

Array (
    [0]=> Array(
        ['customer service'] => -3,
        ['technical support'] => -3
    ),
    [1]=> Array(
        ['picture quality'] => +2,
        ['feature'] => +2
    ),
    [2]=> Array(
        ['smell'] => -2
    ),
    [3]=> Array(
        ['player'] => +2
    ),
    [4]=> Array(
        ['player'] => -3
    ),
    [5]=> Array(
        ['player'] => -3
    ),
    [6]=> Array(
        ['player'] => +2
    ),
    [7]=> Array(
        ['format'] => +2,
        ['progressive scan'] => -2
    ),
);

Since I am very new to regex and php. Any help would be greately apriciated.

Upvotes: 2

Views: 70

Answers (3)

anubhava
anubhava

Reputation: 784998

You can use this code to get your result array:

$out = array();
foreach ($arrayOfString as $k => $v) {
    if (preg_match_all('/\b([^\[\]]+?)\[([+-]?\d+)\] */', $v, $matches))
        $out[$k] = array_combine ( $matches[1], $matches[2] );
}

Online Working Demo: http://ideone.com/nyE4AW

Upvotes: 1

revo
revo

Reputation: 48711

preg_match_all("/([\w ]+[^[]]*)\[([+-]\d*?)\]/", implode(",", $arrayOfString) , $matches);
$result = array_combine($matches[1], $matches[2]);
print_r($result);

Output:

Array
(
    [customer service] => -3
    [ technical support] => -3
    [picture quality] => +2
    [feature] => +2
    [smell] => -2
    [player] => +2
    [dvd player] => -2
    [format] => +2
    [progressive scan] => -2
)

Upvotes: 0

Barmar
Barmar

Reputation: 780798

$result = array();
foreach ($arrayOfString as $i => $string) {
    preg_match_all('/\b(.+?)\[(.+?)\](?:\[.*?\])*/', $string, $match);
    $subarray = array();
    for ($j = 0; $j < count($match[1]); $j++) {
        $subarray[$match[1][$j]] = $match[2][$j];
    }
    $result[$i] = $subarray;
}

Upvotes: 3

Related Questions