[英]Parse ImageMagick histogram color string and populate associative array
[英]parse ImageMagick histogram string output with php
使用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數組結束:
數組([黑色] => 12422,[白色] => 488568)
任何人都可以向我展示在PHP中執行此操作的有效方法嗎?
在shell上運行此命令的輸出格式如下
196:(0,0,0)黑色
500794:(255,255,255)白色
謝謝
試試這個。。希望這能...
$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);
具有一個正則表達式的緊湊版本:
<?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){
[“ black”] =>字符串(5)“ 12422”
[“ white”] =>字符串(6)“ 488568”
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.