使用php解析ImageMagick直方图字符串输出

时间:2016-02-12 11:22:09

标签: php regex imagemagick

使用passthru运行此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数组:

阵 (     [black] => 12422,     [白] => 488568 )

有人能用PHP向我展示一种有效的方法吗?

在shell上运行此输出的输出格式为
196:(0,0,0)黑色
500794:(255,255,255)白色

由于

2 个答案:

答案 0 :(得分:1)

尝试这个..希望这有效......

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

答案 1 :(得分:1)

带有一个正则表达式的紧凑版本:

{{1}}

结果:

  

数组(2){
  [“black”] => string(5)“12422”
  [“white”] => string(6)“488568”
  }