tags:

views:

100

answers:

2

My so far not so bad version to implement this is:

function bashFileConvert($file)
{
    return preg_replace('/([^\/\s]+\s+[^\/]+)(\/|$)/','"${1}"${2}',$file);
}

which mostly processes the problem when there is a space in file name,like

$flie = '/usr/local/my test file.txt'

while will not be recognizable for bash,

so need to convert to

$file = '/usr/local/"my test file.txt"'

before callintg something like :

exec('ls ' . $file);

But there is still many other corner cases,like quote and '&' problem,

so,is there a ready version to do this job?

==================================

Now I tried escapeshellarg(),but a little strange here:

$file = '/usr/local/apache2/resumes_txt/5/San Francisco/qtzhang/Device "Engineer"/Job Resume Qintao Zhang.pdf.txt';
echo escapeshellarg($file);

D:\\test>php test.php
"/usr/local/apache2/resumes_txt/5/San Francisco/qtzhang/Device  Engineer /Job Resume Qintao Zhang.pdf.txt"

seems with this function,quote is replaced with a space?

+3  A: 

The solution is to use the escapeshellarg function in php (http://uk.php.net/manual/en/function.escapeshellarg.php):

$file = escapeshellarg('/usr/local/my test file.txt');

exec('ls ' . $file);

It will wrap quotes round it and escape quotes for you.

Kazar
What if there is a " in file itself?
Shore
Good point, remembered a better solution - edited.
Kazar
Seems " is replaced with a space by this function?I've updated my post
Shore
You are running windows here - windows does not allow double quotes in filenames, that is probably why escapeshellarg replaces them with spaces. Linux has no such limitation, so the quotes remain (I have tested this).
Kazar
Great!Thanks a ton:)
Shore
A: 

If you're trying to automate conversion to such a different language, you're in trouble.

grawity
I'm trying to solve the trouble:)
Shore