douxing5199
douxing5199
2012-02-02 14:14

PHP Exec()使用sed给出了奇怪的结果

已采纳

I have a list of full file paths. All of the full file paths look like "/dir1/dir2/dir3/s..". I want to completely remove the s. from the filename. There is the possibility of a filename being plural, for example s.asdfs.cpp. I do not want to remove the second occurence of s. since that is part of the actual filename and not a reoccuring theme in every full file path in the list.

Running the following in shell works as I want it to:

echo /dir1/dir2/dir3/s.filenames.cpp | sed 's#\(.*\)\/s\.\([^\/]*\)#\1\/\2#g'

Gives the desired result of:

/dir1/dir2/dir3/filenames.cpp

But if I run the following in php:

$formatted_filename = exec("echo ".$filename." | sed 's#\(.*\)\/s\.\([^\/]*\)#\1\/\2#g'");

where

$filename = /dir1/dir2/dir3/s.filenames.cpp;

And then in my bash shell run

php -q script_name_that_contains_command_above.php > test.html

and refresh my firefox browser that displays test.html I get very strange results. In place of where this edited file path should be listed I get

<strange box>/<strange box> 

where

<strange box> 

is a small box with 2 rows and 2 columns consisting of 0's except for the bottom right cell. The first occurence has a 1 in the bottom right cell, and the second occurence has a 2 in the bottom right cell.

The sed command works, but php, or the exec command is interpreting it incorrectly I believe. Any ideas?

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

1条回答

  • duanli0687 duanli0687 9年前

    The solution for using exec with this particular regular expression was to use the php function, preg_replace()

    preg_replace("/\/s/./", "/", $filename);
    
    点赞 评论 复制链接分享