reg exp matching/replacing
| From: | Jennifer Swofford | Date: | Wed, 02 Oct 2002 22:09:03 +0000 |
| Subject: | reg exp matching/replacing | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-118669@lists.php.net to get a copy of this message | ||
I'm getting much closer to achieving my goal here. Now, I'm missing yet one more element.
Here is my code:
----------
$filename = "newexample.html";
$fd = fopen ($filename, "r");
$contents = fread ($fd, filesize ($filename));
preg_match_all('{\/*[A-z0-9_/-]+(.gif|.jpg)}', $contents, $matches);
for ($i=0; $i< count($matches[0]); $i++) {
echo "matched: ".$matches[0][$i]."<br>\n";
$blah = basename($matches[0][$i]);
$contents = eregi_replace('\/*[A-z0-9_/-]+(.gif|.jpg)', $blah, $contents);
}
print $contents;
fclose ($fd);
----------
In this PHP script I am reading in the contents from "newexample.html", going through it
and looking for image strings ("something/.../imagename.gif|jpg"), and stripping them down
to their basenames ("imagename.gif|jpg"). What I must ALSO do is print the contents of
the html file with the new, stripped down image strings. What's going on in the above code is
that each time you get to:
$contents = eregi_replace('\/*[A-z0-9_/-]+(.gif|.jpg)', $blah, $contents);
it goes through the entire html file and replaces every image string with the same replacement, so
when the script is done executing, every image string in the html file is identical. Of course,
what I *want* to do is replace them all individually. So if the html file has:
<img src="images/imagename.gif">
<img src="imagename2.jpg">
<img src="images/2/imagename3.gif">
I want those strings to be replaced with:
<img src="imagename.gif">
<img src="imagename2.jpg">
<img src="imagename3.gif">
But, the code as I have it is just replacing them all with <img
src="imagename3.gif"> since it was the last one to have matched.
How might I go through and replace them one by one? Obscure hints are welcome. :)
Thanks,
Jen