简体   繁体   中英

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.

$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;
}

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

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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