Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

putting shell_exec() output into array [duplicate]

Tags:

arrays

php

I have a line of php :

$output = shell_exec('ps aux | grep 9902 | awk \'{print $11" "$2}\'');

print $output; will give the output :

rtmpgw 10089
/usr/bin/vlc 10107
sh 10123
grep 10125

I tried using this next line to put the above output into an array.

$oparray = explode(" ", trim($output));

It works, but not as expected. print_r($oparray); will give the following output :

Array
(
    [0] => rtmpgw
    [1] => 10089
/usr/bin/vlc
    [2] => 10107
sh
    [3] => 10123
grep
    [4] => 10125
)

This confuses me as I would expect an Index number for each value but three of the values appear to be without indices.

So I suppose my question here is two parts

  1. What is going on in the output above
  2. Can anyone help me get a useful array that looks like this :

    Array
    ( [0] => rtmpgw [1] => 10089 [2] => /usr/bin/vlc [3] => 10107 [4] => sh [5] => 10123 [6] => grep [7] => 10125 )

Thanks~

like image 687
BryanK Avatar asked Dec 07 '25 23:12

BryanK


2 Answers

Try this:

<?php
$text = 'rtmpgw 10089
/usr/bin/vlc 10107
sh 10123
grep 10125';

$oparray = preg_split("#[\r\n]+#", $text);

print_r($oparray);
?>
Array
(
    [0] => rtmpgw 10089
    [1] => /usr/bin/vlc 10107
    [2] => sh 10123
    [3] => grep 10125
)
like image 190
Jason OOO Avatar answered Dec 09 '25 14:12

Jason OOO


The lines in shell_exec output are separated by the end-of-line symbol - and that's different from normal whitespace, that's why explode doesn't account for it.

You can use preg_split instead, with \s character class matching both normal whitespace and EOL.

$oparray = preg_split('/\s+/', trim($output));
like image 35
raina77ow Avatar answered Dec 09 '25 14:12

raina77ow