用php解析ImageMagick直方图字符串输出
使用passthru运行此shell命令时:用php解析ImageMagick直方图字符串输出,php,regex,imagemagick,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数组,如下所示: 排列 ( [黑色]=>12422, [白色]=>488568 ) 有人能告诉我一种用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实现这一点的有效方法吗
在shell上运行此命令的输出格式如下196:(0,0,0)黑色
500794:(255255255)白色
谢谢,试试这个。。希望这能奏效
$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);
试试这个。。希望这能奏效
$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>';
?>
结果:
数组(2){[“黑色”]=>字符串(5)“12422”
[“白色”]=>字符串(6)“488568”
}
带有一个正则表达式的精简版本:
<?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”
}
你试过什么正则表达式?应该很简单。你用过什么正则表达式?这应该非常简单。谢谢,当我像你的例子中那样传递$string时,这确实有效,但是当我使用passthru命令的输出时,它失败了。我认为结果之间可能有换行符/CR。请使用shell_exec而不是passhtru,然后使用preg_replace('~[:cntrl:]~','$string)删除控制字符。谢谢,当我像您的示例中那样传递$string时,这确实有效,但是当我使用passthru命令的输出时,它会失败。我认为结果之间可能有换行符/CR。使用shell_exec而不是passhtru,然后使用preg_replace(“~[:cntrl:]~”,“$string”)删除控制字符。这也适用于:)但不适用于passthru的输出。这也适用于:)但不适用于passthru的输出。