对preg_replace的多次调用会改变结果

时间:2010-03-26 22:14:09

标签: php regex preg-replace

我有一堆以某种标准格式命名的文件。标准表格基本上是这样的:

[integer] _word1_word2_word3_ ... _wordn其中一个单词可以是任何东西,但所有单词都用下划线分隔。

我想对文本做三件事:

1。)我想修改始终在开头的整数,这样“200”之类的东西就会变成$ 200.00。

2。)将“with”,“With”,“w /”或“W /”形式的任何“单词”替换为“with”。

3.)用空格替换所有下划线。

我写了三个不同的preg_replace调用来做这个技巧。它们如下:

1。)$filename = preg_replace("/(^[0-9]+)/","$ $1.00",$filename)

2。)$filename = preg_replace("/_([wW]|[wW]ith)_/"," with ",$filename)

3。)$filename = preg_replace("/_/"," ",$filename);

每个替换在单独运行时按预期工作,但是当所有三个都运行时,将忽略第二个替换。为什么会出现这种情况?

感谢您的帮助!

更新

以下是我正在使用的实际代码:

$path = "./img";
$dir_handle = @opendir($path);
while ($file = readdir($dir_handle)) {
    if ($file != "." && $file != "..") {
        $id = preg_replace("/\.jpg/","",$file);
        $id = preg_replace("/(^[0-9]+)/","$ $1.00", $id);
        $id = preg_replace("/_([wW]\/|[wW]ith)_/"," with ", $id);
        $id = preg_replace("/_/"," ", $id);
        echo "<a href='javascript:show(\"img/$file\")'>$id</a> <br/>";
    }
}
closedir($dir_handle);

1 个答案:

答案 0 :(得分:2)

如果第一个替换删除了第二个替换匹配的文本,则可能会出现类似的情况。但我不认为这就是这里发生的事情。我想你第二次替换时只是出错了。看起来你错过了/

$filename = preg_replace("/_([wW]\/|[wW]ith)_/"," with ", $filename);

在此更改后,似乎工作正常:

$filename = "200_word1_w/_word2";
$filename = preg_replace("/(^[0-9]+)/","$ $1.00", $filename);
$filename = preg_replace("/_([wW]\/|[wW]ith)_/"," with ", $filename);
$filename = preg_replace("/_/"," ", $filename);
print_r($filename);

结果:

$ 200.00 word1 with word2