当使用直通运行此 shell 命令时:
convert example.pdf -threshold 50% -format %c histogram:info:- 2>/dev/null
我在PHP脚本中得到这样的字符串:
12422: ( 0, 0, 0) black 488568: (255,255,255) white
我想得到一个这样的PHP数组:
数组( [黑色] => 12422, [白色] => 488568)
谁能告诉我一种在 PHP 中做到这一点的有效方法?
在 shell 上运行的输出的格式如下
196: ( 0, 0, 0) 黑色
500794:(255,255,255) 白色
谢谢
一个带有一个正则表达式的紧凑版本:
<?php
$string = '12422: ( 0, 0, 0) black 488568: (255,255,255) white';
$newarray = array();
preg_match_all('/(['d]*?):.*?'(.*?')[ ]*?([^'d]*)/i', $string, $regs, PREG_SET_ORDER);
for ($xi = 0; $xi < count($regs); $xi++) {
$newarray[trim($regs[$xi][2])] = trim($regs[$xi][1]);
}
echo '<pre>'; var_dump($newarray); echo '</pre>';
?>
结果:
array(2) {
["黑色"]=>字符串(5) "12422"
["白色"]=>字符串(6) "488568"
}
试试这个。希望这有效...
$string='12422: ( 0, 0, 0) black 488568: (255,255,255) white';
preg_match_all('/(['d]+.*?[a-zA-Z]+)/',$string,$matches);
$result=array();
foreach($matches[1] as $value)
{
preg_match('/['w]+$/',$value,$matches1);
preg_match('/^['d]+/',$value,$matches2);
$result[$matches1[0]]=$matches2[0];
}
print_r($result);