2014-12-11 08:27 阅读 78

php shell_exec正则表达式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 'FOO\s*ONE'"); :

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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

4条回答 默认 最新

  • 已采纳
    duandie0921 duandie0921 2014-12-11 08:55

    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.

    点赞 评论 复制链接分享
  • ds15812330851 ds15812330851 2014-12-11 08:30

    You have to escape the \ character with an other \, so it becomes:

     shell_exec("sh 'FOO\\s*ONE'");
    点赞 评论 复制链接分享
  • doucongmishang2385 doucongmishang2385 2014-12-11 08:30

    You need to escape the backslash:

    shell_exec("sh 'FOO\\s*ONE'");
    点赞 评论 复制链接分享
  • duanjipiao7076 duanjipiao7076 2014-12-11 08:50

    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 %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().

    点赞 评论 复制链接分享