How can dynamic values be correctly parsed and stored in an array when dealing with the output of a traceroute command in PHP?

When dealing with the output of a traceroute command in PHP, dynamic values such as IP addresses or hop counts need to be correctly parsed and stored in an array. One way to achieve this is by using regular expressions to extract the desired values from the output string and then store them in an array for further processing.

<?php
// Example output of traceroute command
$output = "1 192.168.1.1 2ms\n2 10.0.0.1 5ms\n3 8.8.8.8 10ms";

// Initialize an empty array to store parsed values
$tracerouteResults = [];

// Use regular expression to extract hop count and IP address
preg_match_all("/(\d+)\s([0-9.]+)\s(\d+)ms/", $output, $matches, PREG_SET_ORDER);

// Store extracted values in the array
foreach ($matches as $match) {
    $hop = $match[1];
    $ip = $match[2];
    $time = $match[3];
    
    $tracerouteResults[] = [
        'hop' => $hop,
        'ip' => $ip,
        'time' => $time
    ];
}

// Print the parsed results
print_r($tracerouteResults);
?>