抱歉,如果我误解了这个问题,我认为这可能是您正在寻找的答案... :)
版本 1:
#executes the comand and stores in array
$testExec = exec("df -h --total" ,$testArray);
#moves to the end off the array
$testArrayEnd = end($testExec);
#splits the last line into an array
$stringArray = explode(' ',$testArrayEnd);
foreach($stringArray as $string){
#checks if the string contains a %
if (preg_match("/%/", $string)) {
#there is only one % so this is what you're looking for
$percentage = $string;
var_dump($percentage);
}
}
PS。@ReynierPM您不需要shell_exec来获得完整的输出返回...您只需要定义一个要在其中存储数据的数组... :)并授予它不是字符串,但您可以轻松地对其进行转换使用implode() 合二为一
版本 2:
抱歉,如果您不同意,但我在编辑@Nazariy 答案时感到不舒服,因为我正在添加/更改很多内容(在此阶段请参阅编辑历史:)。
#thanks go out to ReynierPM
#returns string with every entry being separated by a newline
$output = shell_exec('df -h --total');
$ArrayFull=(array_map(function($line){ /*<-- *¹ & *² */
$elements=preg_split('/\s+/',$line); /*<--- *4 */>
return(array(
'filesystem' => $elements[0],
'1k-blocks' => $elements[1],
'used' => $elements[2],
'available' => $elements[3],
'use%' => $elements[4],
'mounted_on' => $elements[5]
));
},explode("\n",$output))); /*(<--- *³)*/
#removes bloat
unset($ArrayFull[0]);
#Rebase array keys https://stackoverflow.com/questions/5943149/rebase-array-keys-after-unsetting-elements
$ArrayFull=array_values($ArrayFull);
#if you only want the last value ;)
$lastVallue = end($ArrayFull);
解释:
*¹
array_map也将它应用于数组中的所有值 "array_map — 将回调应用于给定数组的元素"
*²
我们首先给它一个回调函数,它将为每个元素调用,并将变量传递给它 $line (我们用它来存储由explode创建的行)
*³
我们使用array_maps来分解\n(为每个新行创建一个数组条目)(我们当然对$data进行explode)
*4
所以现在每个行被分离... 我们将分离的行拆分为子字符串并将它们存储在新变量中。preg_split('/\s+/',$line) 将 $line 拆分为一个数组,而无需处理多个空白的问题。s 代表空间。
抱歉格式化...将编辑后者:)