2013-03-06 65 views
-1

我有PHP 4代碼來檢查兩個文件的差異,這在PHP 4版本的舊服務器上正常工作,但在新服務器上出現錯誤。例如:PHP 4代碼給錯誤php 5

$maxlen是沒有定義的

而且功能不工作新的服務器上。任何人都知道如何改變這個最近的PHP版本?

function diff($old, $new){ 
      foreach($old as $oindex => $ovalue){ 
        $nkeys = array_keys($new, $ovalue); 
        foreach($nkeys as $nindex){ 
          $matrix[$oindex][$nindex] = isset($matrix[$oindex - 1][$nindex - 1]) ? 
            $matrix[$oindex - 1][$nindex - 1] + 1 : 1; 
          if($matrix[$oindex][$nindex] > $maxlen){ 
            $maxlen = $matrix[$oindex][$nindex]; 
            $omax = $oindex + 1 - $maxlen; 
            $nmax = $nindex + 1 - $maxlen; 
          } 
        }   
      } 
      if($maxlen == 0) return array(array('d'=>$old, 'i'=>$new)); 
      return array_merge( 
        diff(array_slice($old, 0, $omax), array_slice($new, 0, $nmax)), 
        array_slice($new, $nmax, $maxlen), 
        diff(array_slice($old, $omax + $maxlen), array_slice($new, $nmax + $maxlen))); 
    } 

    function htmlDiff($old, $new){ 
    $preg="/[\s,]+/"; 
     $old=str_replace(">","> ",$old); 
     $new=str_replace(">","> ",$new); 
     $old=str_replace("<"," <",$old); 
     $new=str_replace("<"," <",$new); 

     $diff = diff(preg_split($preg, $old),preg_split($preg, $new)); 
     foreach($diff as $k){ 
     if(is_array($k)) 
      $ret .= (!empty($k['d'])?"<div style='BACKGROUND-COLOR: red'>".implode(' ',$k['d'])."</div> ":''). 
      (!empty($k['i'])?"<div style='BACKGROUND-COLOR: yellow'>".implode(' ',$k['i'])."</div> ":''); 
      else $ret .= $k . ' '; 
     } 
     return $ret; 
    } 
    function creatediff($oldurl,$newurl,$diffurl){ 
     $sold= file_get_contents($oldurl); 
     $snew= file_get_contents($newurl); 
     $diff=htmlDiff($sold,$snew); 
     $diff=preg_replace('#(href|src)="([^:"]*)("|(?:(?:%20|\s|\+)[^"]*"))#','$1="'.$newurl.'/$2"',$diff); 
     file_put_contents($diffurl,$diff); 
    } 
+1

試過手冊? http://php.net/manual/en/faq.migration5.php – Repox 2013-03-06 18:13:56

+0

http://stackoverflow.com/questions/2487021/what-is-the-difference-betwen-variable-in-php4-and-php5 – apoq 2013-03-06 18:14:39

+0

你從哪裏得到'$ maxlen'? – codingbiz 2013-03-06 18:14:41

回答

1

這不是由於版本差異,而是代碼錯誤。您之前安裝時可能會拒絕/關閉error_reporting,這很可能是您沒有看到它的原因。返回到您的PHP4環境,將error_reporting設置爲E_ALL,您可能會看到大部分相同的警告。

因爲$maxlen僅在滿足一個特定的if條件時才定義,所以在其他情況下永遠不會定義它,並生成警告。您可以通過在函數頂部定義$maxlen或在嘗試引用變量之前使用isset()來避免這種情況。

+0

是的,我做的所有事情上的PHP 5,但沒有工作 – 2013-03-07 15:53:57

1

您的循環包含:

if($matrix[$oindex][$nindex] > $maxlen) 

但第一次循環,$maxlen沒有設定任何目標,因此這種比較生成一個警告(不是錯誤)。

您應該在循環之前初始化$maxlen,或將其更改爲:

if (!isset($maxlen) || $matrix[$oindex][$nindex] > $maxlen) 

另一個問題是,有一個在功能上沒有$matrix陣列。如果這是一個全局變量,則需要:

global $matrix; 

函數的開頭。

+0

我編輯了這樣的腳本仍然不能使用PHP 5 – 2013-03-07 15:54:32

+0

你仍然收到'$ maxlen'未定義的警告? – Barmar 2013-03-07 16:22:59