简体   繁体   中英

php shell_exec regular expression PCRE/POSIX

I have a problem with my php-script when I call shell_exec and pass a regular expression .

PHP code :

shell_exec("sh myscript.sh 'FOO\s*ONE'");

myscript.sh :

result=$(grep -c "${1}"  myLongFile.txt)
echo ${result}

Like this, it returns 0 but if il call directly with cmd grep -c "FOO\\s*ONE" myLongFile.txt it returns 23 .

And if i replace in my php script \\s by the class [[:space:]] it's working, but I have to use \\s

I tried many solutions but failed.

您必须使用另一个\\来转义\\字符,因此它变为:

 shell_exec("sh myscript.sh 'FOO\\s*ONE'");

您需要转义反斜杠:

shell_exec("sh myscript.sh 'FOO\\s*ONE'");

The problem is not the escaping, but simply because grep is POSIX based; this is why you should use [[:space:]] instead of \\s . Some versions of grep support PCRE syntax using the -P option, but using POSIX is more portable.

Also, if you want to pass a variable from PHP to a shell script it's advisable to use escapeshellarg() :

$re = 'FOO[[:space:]]*ONE';
shell_exec(sprintf("sh myscript.sh %s", escapeshellarg($re)));

It should be mentioned that escapeshellarg() doesn't work consistently between Windows and Linux (and even between shells); in some cases you need to apply addcslashes() .

Thank you all,

I find the solution, i just add option -P for grep in my script like this :

result=$(grep -P -c "${1}"  myLongFile.txt)

Now, i can use \\s

-P, --perl-regexp Interpret PATTERN as a Perl regular expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM