在HTML页面中使用新名称查找并替换所有出现的旧图像名称

After I rename an image I would like to perform a search on all HTML Pages within a directory. The idea is to find all pages with the old name and update the page with new name.

I am having a problem with the string replacement portion.

$files = glob('/directory/*.html');
foreach($files AS $file) {
   $html = file_get_contents($file);
   $find = "old.jpg";
   preg_match("#src=(\"?|'?)(http://www.domain.com/images/|/images/)?$find(\"?|'?)#si", $html, $image);
   if (!empty($image[1])) {

       //find and replace all occurrences within page I need help with.

       $write = fopen($file, 'w');
       fwrite($write, $new_html);
       fclose($write);
    }
}

Examples of what I am searching for and replacing.

Find src="/images/old.jpg" replace src="/images/new.jpg"

Find src="http://www.domain.com/images/old.jpg replace src="http://www.domain.com/images/new.jpg"

Find src="/old.jpg ignore

Find src="http://www.anyotherdomain/old.jpg ignore

A FAR superior solution would be to include a constant with the image name in every webpage and use ti to reference your image path.

constants.inc.php

<?php
    define('IMAGE_PATH', 'absolute/path/to/image.jpg');
?>

anyotherpage.php

<?php require_once('constants.inc.php'); ?>
...
...
...
<img src="<?php echo IMAGE_PATH ?>">

Replace in Files

It's probably easiest to just do a find and replace in files using a text editor that supports it.

There is similar functionality in many IDEs (usually "find in files" or "find in project"), but there's more setup involved if you aren't using them already.

Using PHP

If you absolutely have to use PHP you'll want to use preg_replace(). You can test your regex using a regex tool like RegexBuddy or Rubular (there are tons of regex testers online), or a text editor that supports regex.

Two bits of advice

  1. Backup or version your files before you batch modify them like this.
  2. Don't be afraid to search / replace with multiple patterns to get all of the different cases.