【问题标题】:Multiple calls to preg_replace alters result多次调用 preg_replace 会改变结果
【发布时间】:2013-09-30 00:09:32
【问题描述】:

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

[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);

【问题讨论】:

  • 对我来说很好。你能发布更多代码,以及一个不起作用的文本示例吗?

标签: php regex preg-replace


【解决方案1】:

如果第一个替换删除了第二个替换匹配的某些文本,则可能会发生类似的情况。但我不认为这就是这里正在发生的事情。我认为您在第二次更换时出现了错误。看起来您缺少/

$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 和 word2

【讨论】:

  • 我实际上注意到我认为的“w/”实际上只是没有斜线的“w”。这就是它之前工作的原因......但是在我复制并粘贴您的代码并删除“\ /”之后,它工作了!我不知道为什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-06
  • 2021-02-10
  • 2013-11-06
相关资源
最近更新 更多