2016-02-12 112 views
0

ImageMagick的直方图输出字符串使用中继运行这个shell命令:解析用PHP

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中?

在壳运行此输出被格式化等
196:(0,0,0)黑色
500794:(255255255)白色

由于

+0

您尝试了什么正则表达式?它应该是非常简单的。 – neuhaus

回答

1

压缩版本与一个正则表达式:

<?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>'; 
?> 

结果:

阵列(2){
        [ “黑”] =>串(5) “12422”
        [ “白色”] =>字符串(6)“488568”
}

+0

This works too :)但与我的passthru输出不同。 – garethmurton

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); 
+0

谢谢,当我像你的例子中那样传递$ string的时候,它会工作,但是当我使用passthru命令的输出时失败。我认为结果之间可能有换行符/ CR。 – garethmurton

+0

解决使用shell_exec而不是passhtru,然后使用preg_replace('〜[[:cntrl:]]〜','',$ string)删除控制字符 – garethmurton