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

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

我想提取“[”和“]”内的每个单词和关联的数值(只有数字而不是大括号内的字符串,但包括极性符号)。因此输出数组必须如下所示:

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

因为我对正则表达式和 php 非常陌生。任何帮助将不胜感激。

最佳答案

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

关于php - 如何在php中使用正则表达式从字符串中获取带符号的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21520055/

相关文章:

php - 如何统计项目数量

php - HTMLPurifier 破坏图像

apache - 许多 php-fpm : pool www processes running but Apache isn't

java - 删除 CSV 文档中字段开头和结尾的引用

c# - .NET 正则表达式 : negate previous character for the first character in string

php - 我如何为一个类别实现这个基本 CSS?

php - 无法在 Plesk 上运行 pdflatex 命令 (Tex Live)

regex - 匹配新行,为什么 [.\n]* 在正则表达式中不起作用?

regex - Microsoft Excel 中的正则表达式子字符串替换

python - 在 views.py Django 中使用正则表达式?