2012-02-02 29 views
0

我有一個完整的文件路徑列表。所有完整的文件路徑看起來像「/ dir1/dir2/dir3/s ..」。我想徹底刪除s。從文件名。文件名有可能是複數,例如s.asdfs.cpp。我不想刪除秒的第二次發生。因爲這是實際文件名的一部分,而不是列表中每個完整文件路徑中的重複主題。PHP執行()使用Sed給出奇怪的結果

跑在外殼的作品下面,我希望它:

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

給出了期望的結果:

/dir1/dir2/dir3/filenames.cpp 

但是,如果我跑在PHP如下:

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

其中

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

然後在我的bash shell中運行

php -q script_name_that_contains_command_above.php > test.html 

,並刷新顯示的test.html我得到非常奇怪的結果我的Firefox瀏覽器。在地方,這些修改的文件路徑應列出我得到

<strange box>/<strange box> 

其中

<strange box> 

是2行2列由0的除了右下角細胞的小盒子。第一次出現在右下角的單元格中有1,第二次出現在右下角的單元格中有2。

sed命令有效,但php或exec命令正在解釋它我認爲不正確。有任何想法嗎?

+0

你爲什麼不使用PHP的正則表達式? – 2012-02-02 14:16:29

+0

我對PHP很新穎。你在暗示preg_match函數嗎? – halexh 2012-02-02 14:21:31

+0

對於不可打印的字符,「奇怪的盒子」可能是「未知字符」字形字形。可能是null(ascii 0)。 – 2012-02-02 14:25:02

回答

0

使用Exec用這個特定的正則表達式的解決方案是使用PHP函數,preg_replace()

preg_replace("/\/s/./", "/", $filename);