$url = "http://www.timeschina.com/";
$pattern = "/<img\s+?(.+)src=(\"|\')??([^\"\'[:space:]]+?)(\"|\')??([^>]*?)>/iU";
$contents = '<img src="images/a.gif" width="12" height="23">';
echo htmlspecialchars(preg_replace($pattern, "<img \\1 src=\"".$url."\\3\"\\5>", $contents));$contents = '<img width="12" height="23" src="images/a.gif">';
echo htmlspecialchars(preg_replace($pattern, "<img \\1 src=\"".$url."\\3\"\\5>", $contents));$contents = '<img src="images/a.gif">';
echo htmlspecialchars(preg_replace($pattern, "<img \\1 src=\"".$url."\\3\"\\5>", $contents));

解决方案 »

  1.   

    還是要加上從文件中把內容讀出,替換後再寫入文件。
    參攷
    http://expert.csdn.net/Expert/TopicView1.asp?id=1267960
    哈哈。
      

  2.   

    function replace($file, $url = "http://www.timeschina.com/")
    {
      $contents = implode("", file($file));
      $pattern = "/<img\s+?(.+)src=(\"|\')??([^\"\'[:space:]]+?)(\"|\')??([^>]*?)>/iU";
      echo preg_replace($pattern, "<img \\1 src=\"".$url."\\3\"\\5>", $contents);
      $fp = fopen($file, "w");
      fwrite($fp, $contents);
      fclose($fp);
    }然后循环读取一个目录调用这个函数即可。
      

  3.   

    写错了,多了一个echo 
    function replace($file, $url = "http://www.timeschina.com/")
    {
      $contents = implode("", file($file));
      $pattern = "/<img\s+?(.+)src=(\"|\')??([^\"\'[:space:]]+?)(\"|\')??([^>]*?)>/iU";
      preg_replace($pattern, "<img \\1 src=\"".$url."\\3\"\\5>", $contents);
      $fp = fopen($file, "w");
      fwrite($fp, $contents);
      fclose($fp);
    }
      

  4.   

    用 EditPlus 编辑器查找然后再替换:)
      

  5.   

    又写错了,好久没写代码都快生疏了,哎!无奈!:(
    function replace($file, $url = "http://www.timeschina.com/")
    {
      $contents = implode("", file($file));
      $pattern = "/<img\s+?(.+)src=(\"|\')??([^\"\'[:space:]]+?)(\"|\')??([^>]*?)>/iU";
      $result = preg_replace($pattern, "<img \\1 src=\"".$url."\\3\"\\5>", $contents);
      $fp = fopen($file, "w");
      fwrite($fp, $result);
      fclose($fp);
    }
    该死的CSDN,明明没有超过连续3个回复,却报错,真是的。