2017-01-20 95 views
-2

我需要比較兩個文本總是相同的,但15 0 20個單詞將被其他文本替換。我如何比較這兩個文本並打印出已被替換的文字?提取兩個文本之間改變的所有單詞PHP

1大家好,我的朋友,這是一個計算器問題
2你好的男人,這是引用了網絡

結果: 我的朋友 - >男人
問題 - >引用
計算器 - >網絡

謝謝大家

+3

添加你有這麼遠,看你已經嘗試了代碼。 – MONZTAAA

回答

0

因此,一種方法是確定每串有共同點的話。然後,對於每個文本,捕獲常用單詞之間的字符。

function findDifferences($one, $two) 
{ 
    $one .= ' {end}'; // add a common string to the end 
    $two .= ' {end}'; // of each string to end searching on. 

    // break sting into array of words 
    $arrayOne = explode(' ', $one); 
    $arrayTwo = explode(' ', $two); 

    $inCommon = Array(); // collect the words common in both strings 
    $differences = null; // collect things that are different in each 

    // see which words from str1 exist in str2 
    $arrayTwo_temp = $arrayTwo; 
    foreach ($arrayOne as $i => $word) { 
     if ($key = array_search($word, $arrayTwo_temp) !== false) { 
      $inCommon[] = $word; 
      unset($arrayTwo_temp[$key]); 
     } 
    } 

    $startA = 0; 
    $startB = 0; 

    foreach ($inCommon as $common) { 
     $uniqueToOne = ''; 
     $uniqueToTwo = ''; 

     // collect chars between this 'common' and the last 'common' 
     $endA = strpos($one, $common, $startA); 
     $lenA = $endA - $startA; 
     $uniqueToOne = substr($one, $startA, $lenA); 

     //collect chars between this 'common' and the last 'common' 
     $endB = strpos($two, $common, $startB); 
     $lenB = $endB - $startB; 
     $uniqueToTwo = substr($two, $startB, $lenB); 

     // Add old and new values to array, but not if blank. 
     // They should only ever be == if they are blank '' 
     if ($uniqueToOne != $uniqueToTwo) { 
      $differences[] = Array(
       'old' => trim($uniqueToOne), 
       'new' => trim($uniqueToTwo) 
      ); 
     } 

     // set the start past the last found common word 
     $startA = $endA + strlen($common); 
     $startB = $endB + strlen($common); 
    } 

    // returns false if there aren't any differences 
    return $differences ?: false; 
} 

然後,它的顯示,但是你想要的數據一件小事:

$one = '1 Hi my friend, this is a question for stackoverflow'; 
$two = '2 Hi men, this is a quoted for web'; 

$differences = findDifferences($one, $two); 

foreach($differences as $diff){ 
    echo $diff['old'] . ' -> ' . $diff['new'] . '<br>'; 
} 

// 1 -> 2 
// my friend, -> men, 
// question -> quoted 
// stackoverflow -> web 
相關問題