Reputation: 597
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);
Upvotes: 0
Views: 167
Reputation: 838226
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 /
:
$filename = preg_replace("/_([wW]\/|[wW]ith)_/"," with ", $filename);
After this change it seems to work fine:
$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);
Result:
$ 200.00 word1 with word2
Upvotes: 2