2017-01-20 4 views
-2

Мне нужно сравнить два текста, которые всегда будут одинаковыми, кроме 15 0 20 слов, которые будут заменены другими. Как я могу сравнить эти два текста и распечатать слова, которые были заменены?Извлечь все слова, измененные между двумя текстами PHP

1 Привет мой друг, это вопрос для StackOverflow
2 Привет люди, это в кавычках для веб

Результаты: мой друг -> люди
вопрос -> цитирует
StackOverflow -> веб

Спасибо всем

+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 
Смежные вопросы