2017-01-20 5 views
-2

2つのテキストを比較する必要があります。これらの2つのテキストを比較し、置き換えられた単語を印刷するにはどうすればよいですか? - >男性
質問 - >引用され
のstackoverflow - > 私の友人:2つのテキスト間で変更されたすべての単語を抽出するPHP

1こんにちは私の友人は、これはstackoverflowの
2こんにちは男性、これはウェブのために引用されている

結果について質問ですウェブ

はだからすべて

+3

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; } 

は、その後、それはあなたが欲しいしかし、データを表示するには些細な問題です。 – MONZTAAA

答えて

0

ありがとう、1つのアプローチは、各文字列が共通に持っているものの単語を識別することです。次に、各テキストについて、共通の単語の間の文字をキャプチャします。あなたが試みているものを見るために、これまで持っているコードを追加します

$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 
関連する問題