quick and dirty ... without regular expression ... provided:
$out = "5 minute input rate 134000 bits/sec, 164 packets/sec"
is the string you want to create an array from the following form:
array( 'time' => '5', 'input' => '134000', 'packets'=> '164' );
readable non-regression solution (this can be made shorter, but I want to make it obvious)
1.) getting the text from the beginning to the first appearance of the separator string:
// find time time interval $timeDelimiter = " minute" // set the delimiter $timeEnd = strpos($out, $timeDelimiter); // find the first occurence of delimiter $time = substr($out, 0, $timeEnd)); // set time to substring before delimiter
now separate this part from your line ...
$out = substr($out, $timeEnd + strlen($timeDelimiter)); // strip the processed part from $out
2.) getting text between two lines of delimiter
// find the input interval $inputDelimiterStart = "input rate "; $inputDelimiterEnd = " bits/sec"; $inputStartPos = strpos($out, $inputDelimiterStart) + strlen($inputDelimiterStart); $inputEndPos = strpos($out, $inputEndDelimiter); $input = substr($out, $inputStartPos, $inputEndPos);
then discard again what you have already processed
$out = substr($out, $inputEndPos + strlen($inputDelimiterEnd));
3.) .... the same game for packages ... (I leave it here .. you understand the idea)
now that you have $ time, $ input, $ packets ... output JSON as follows:
echo json_encode( array( 'time' => $time, 'input' => $input, 'packets' => $packets, ) );
You can transfer this material to a function with parameters startDelimiter, endDelimiter and save some code here. The best solution is to use aka regex regular expressions ... but obviously they are harder to learn and not so easy to debug if they don't work the way you want.