NeverPhased NeverPhased - 1 year ago 74
PHP Question

Is there an equivalent function in PHP for unix cut -f?

I have a long string of values separated by tabs and I wish to cut the data as if using unix cut -f. If I use cut -f5 it cuts all my data into a single column of the value which is in the 5th position. Is there a PHP function that can do the same?

Below is an example of the raw file with each word in the row separated by a tab

enter image description here

The result would be as follows if I ran cut -f2:

enter image description here

Answer Source

I guess the answer really is "no", as far as I know. But you can combine a few PHP functions to achieve the same result.

You can use file to read the lines from the file into an array

$rows = file($path_to_your_file);

Then convert that array of strings to a multidimensional array

$rows = array_map(function($row){
    return str_getcsv($row, "\t");
}, $rows);

Then get the column you want from that array.

$column_5 = array_column($rows, 4);

Not as concise as cut -f5, but PHP rarely is for things like this.

Incidentally, if you don't care that your PHP program will only work on systems that have unix cut, you can actually just use the cut -f in shell_exec.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download