我有如下所示的示例字符串数组。
$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/