First, consider this PHP Script:
Code: Select all
-bash-2.05b# cat test.php
<?php
$line1 = '-rwxr-xr-x 1 root root 125 Sep 2 16:40 viewTmp.sh';
$line2 = '-rwxr-xr-x 1 root root 125 Sep 2 16:40 August 2010';
$words1 = explode(" ",$line1);
echo "\$line1 = " ; var_dump($words1);
$words2 = explode(" ",$line2);
echo "\n\$line2 = " ; var_dump($words2);
$fileName1 = $words1[count($words1) - 1];
echo "\nFile Name-1: " . $fileName1;
$fileName2 = $words2[count($words2) - 1];
echo "\nFile Name-2: " . $fileName2;
echo "\n";
?>
-bash-2.05b#Please mind the first two statements which contains file names in them at the end. The first file name is "viewTmp.sh" whereas the second file name consists of two separate words "August 2010":
Code: Select all
$line1 = '-rwxr-xr-x 1 root root 125 Sep 2 16:40 viewTmp.sh';
$line2 = '-rwxr-xr-x 1 root root 125 Sep 2 16:40 August 2010';I want to extract only file names from those lines. Of course, they are going to come from the output of this UNIX statement:
Code: Select all
ls -lOkay, the problem is that I am able to extract the last word but what if there are two or more words separated by white spaces that form a file / directory name?
Here's the output of the above PHP Script:
Code: Select all
-bash-2.05b# php test.php
Content-type: text/html
X-Powered-By: PHP/4.3.10
$line1 = array(11) {
[0]=>
string(10) "-rwxr-xr-x"
[1]=>
string(0) ""
[2]=>
string(1) "1"
[3]=>
string(4) "root"
[4]=>
string(4) "root"
[5]=>
string(3) "125"
[6]=>
string(3) "Sep"
[7]=>
string(0) ""
[8]=>
string(1) "2"
[9]=>
string(5) "16:40"
[10]=>
string(10) "viewTmp.sh"
}
$line2 = array(12) {
[0]=>
string(10) "-rwxr-xr-x"
[1]=>
string(0) ""
[2]=>
string(1) "1"
[3]=>
string(4) "root"
[4]=>
string(4) "root"
[5]=>
string(3) "125"
[6]=>
string(3) "Sep"
[7]=>
string(0) ""
[8]=>
string(1) "2"
[9]=>
string(5) "16:40"
[10]=>
string(6) "August"
[11]=>
string(4) "2010"
}
File Name-1: viewTmp.sh
File Name-2: 2010
-bash-2.05b#As it can be seen above that the second file name is being taken as 2010 instead of August 2010:
Code: Select all
File Name-2: 2010