【发布时间】: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