如何使用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.
我有如下字符串的示例数组。 p>
$ arrayOfString = array(
[0] =>'客户服务[-3]技术支持[-3]',
[1] =>'图片质量[+2]功能[+2]',
[2] =>'闻[-2]',
[3] =>'播放器[+2]',
[4] =>'播放器[-3] [u]' ,
[5] =>'DVD播放器[-2]',
[6] =>'播放器[+2] [p]',
[7] =>'格式[+2 ] [u]逐行扫描[-2]'
);
code> pre>
我想在'['&amp ;;'中提取每个单词和相关的数值。 ']'(只有数字不是那些括号内的字符串,但包括极性符号)。 因此输出数组必须如下所示: p>
Array(
[0] =>数组(
['客户服务'] => -3,
['技术支持'] => -3
),
[1] =>数组(
['图片质量'] => + 2,
['feature'] => ; +2
),
[2] =>数组(
['气味'] => -2
),
[3] =>数组(
['player'] => +2
),
[4] =>数组(
['player'] => -3
),
[5] =>数组(
['播放器 '] => -3
),
[6] =>数组(
['player'] => +2
),
[7] =>数组(
[ 'format'] => + 2,
['progressive scan'] => -2
),
);
code> pre>
因为我 我是regex和php的新手。 任何帮助都会得到很好的帮助。 p>
div>
答
$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
)