如何使用PHP中的正则表达式从字符串中获取带符号的数字

时间:2014-02-03 05:06:03

标签: php regex

我有如下字符串的示例数组。

$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]'
);

我想在'['&amp ;;'中提取每个单词和相关的数值。 ']'(只有数字不是那些括号内的字符串,但包括极性符号)。因此输出数组必须如下所示:

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

因为我对regex和php很新。任何帮助都会得到很好的帮助。

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

您可以使用此代码获取结果数组:

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

在线工作演示:http://ideone.com/nyE4AW

答案 2 :(得分:0)

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

<强>输出

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