多次调用 preg_replace 会改变结果
我有一堆以某种标准格式命名的文件。标准形式基本上是这样的:
[integer]_word1_word2_word3_ ... _wordn 其中单词实际上可以是任何内容,但所有单词都用下划线分隔。
我实际上只想对文本做 3 件事:
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);
I have a bunch of files that were named in a somewhat standard format. The standard form is basically this:
[integer]_word1_word2_word3_ ... _wordn where a word could really be anything, but all words are separated by an underscore.
There is really only 3 things I want to do to the text:
1.) I want to modify the integer, which is always at the beginning, so that something like "200" would become $ 200.00.
2.) replace any "words" of the form "with", "With", "w/", or "W/" with "with".
3.) Replace all underscores with a space.
I wrote three different preg_replace calls to do the trick. They are as follows:
1.) $filename = preg_replace("/(^[0-9]+)/","$ $1.00",$filename)
2.) $filename = preg_replace("/_([wW]|[wW]ith)_/"," with ",$filename)
3.) $filename = preg_replace("/_/"," ",$filename);
Each replacement works as expected when run individually, but when all three are run, the 2nd replacement is ignored. Why would something like that occur?
Thanks for the help!
Update:
Here's the actual code I'm working with:
$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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果第一个替换删除了第二个替换匹配的某些文本,则可能会发生类似的情况。但我不认为这就是这里发生的事情。我认为你只是在第二次更换时出现了错误。看起来您缺少
/
:经过此更改,它似乎工作正常:
结果:
Something like that could occur if the first replacement removes some text that the second replace matches on. But I don't think that's what is happening here. I think you just have an error in your second replacement. It looks like you are missing the
/
:After this change it seems to work fine:
Result: