May be, you can use the following for the second question:
For every $line (in your example $line="this is a test", I suppose, you have a number of such lines, in array or...) you do:
$line_arr=explode(" " ,$line);
$arr_to_sort[$line_arr[1]]=$line;
Now after you go through all $line's you have array of values like:
"is"=>"this is a test"
Now you can use ksort() for $arr_to_sort - read manual about it. But it will work only fpr unique words by which you're sorting, of course.