Php 从数组索引中提取值的特定部分
我有最新的密码Php 从数组索引中提取值的特定部分,php,arrays,Php,Arrays,我有最新的密码 $trace = exec("tracert 192.168.0.1", $outcome, $status); print_r($outcome); 输出的数组如下所示: Array ( [0] => [1] => Tracing route to 192.168.0.1 over a maximum of 30 hops [2] => [3] => 1 <1 ms <1 ms <1 ms 192.168.1.1 [4] =>
$trace = exec("tracert 192.168.0.1", $outcome, $status);
print_r($outcome);
输出的数组如下所示:
Array ( [0] => [1] => Tracing route to 192.168.0.1 over a maximum of 30 hops [2] => [3] => 1 <1 ms <1 ms <1 ms 192.168.1.1 [4] => 2 5 ms 4 ms 4 ms 192.168.0.1 [5] => [6] => Trace complete. )
Array([0]=>[1]=>跟踪路由到192.168.0.1,最多30跳[2]=>[3]=>1次跟踪完成。)
现在我特别想了解的是元素3和4中的延迟值(ms)。我可以使用print_r($output[3])获得这些结果,例如,哪个输出:
1 <1 ms <1 ms <1 ms 192.168.1.1
1您可能需要对此进行调整,但这里有一个开始:
此外,这也适用于原始输出,而不是数组。我将exec()
更改为system()
,并使用输出缓冲区捕获输出。或者,您可以修改代码并在exec的数组的每一行上使用preg\u match
preg_match_all('/(<?[0-9]+ ms <?[0-9]+ ms <?[0-9]+ ms)/i', $subject, $result, PREG_PATTERN_ORDER);
preg\u match\u all('/(使用正则表达式:
<?[0-9]+ ?ms
使用strrpos
可以在字符串中查找子字符串最后一次出现的位置。因此,如果您知道它将始终输出“ms”作为最后一次出现的位置,则可以使用:
$last_occurrence = strrpos($outcome[3], ' ms');
要返回字符串的第一个(无论有多少个)字符,请执行以下操作:
$adjusted_string = substr($outcome[3], 0, $last_occurrence);
编辑:
为了摆脱第一个角色:
echo substr($adjusted_string, 1);
因此,如果您想将其全部分组:
echo substr(substr($outcome[3], 0, strrpos($outcome[3], ' ms')), 1);
如果它保持相同的模式,你可以
list(,$l1,$lu1,$l2,$lu2,$l3,$lu3,) = explode(" ", $outcome[3]);
echo $l1.$lu1.' '.$l2.$lu2.' '.$l3.$lu3;
请参见此处:希望这有助于:
// create array to store the results
$result = array();
// loop through all lines of the outcome
foreach ($outcome as $line)
{
// continue to the next line if there is no "ms" information in the line
if (strpos($line, 'ms') === FALSE)
{
continue;
}
// remove the initial number (counter) from the line
$line = ltrim($line, '0123456789');
// split the string in pieces
$latency_values = explode(' ms ', $line);
// throw away the latest element (IP address)
array_pop($latency_values);
// remove surrounding white spaces
$latency_values = array_map('trim', $latency_values);
// add to our result array
$result[] = $latency_values;
}
// output the result
print_r($result);
此解决方案使用:
- 环路
这些值可能会发生变化-但它会保持相同的模式吗?它会一直是元素3吗?我想你的意思是echo$output[3]
notprint\r
如果您能精确地指定您想要的输出格式,那就更好了……这仍然会包括引导的第一个数字值以及OP正在寻找的延迟值(1
,在他的示例中)@Bernard:如果您想这是可行的,尽管我需要添加一个正斜杠,如下所示:/