2016-09-28 163 views
0

见图片:比较两个字符串,突出重复的单词在PHP

enter image description here

我真的想知道什么是比较上重复的单词两个字符串(长文本文件)的最佳方法,那么我需要在第二个字符串中突出显示它们。就像copyscape一样。它用于我们内部的内部数据库。

我是否缺少一个简单的PHP函数?任何人都可以指向正确的方向吗?

我所知道的是制作两个数组并将它们与foreach循环进行比较。但它没有任何意义,我的脚本越来越没有突出显示40行

回答

0

我认为https://github.com/gorhill/PHP-FineDiff可能会完成这项工作。如果需要,它甚至可以将字符级别的各种粒度的文本进行比较。

实际上,你可以找到共同点重复的短语,如果他们在finediff.php加入

static $commons; 

public static function renderCommonsFromOpcodes($from, $opcodes) 
{ 
    FineDiff::renderFromOpcodes($from, $opcodes, array('FineDiff', 'renderCommonsFromOpcode')); 
} 

private static function renderCommonsFromOpcode($opcode, $from, $from_offset, $from_len) 
{ 
    if ($opcode === 'c') { 
     self::$commons[] = substr($from, $from_offset, $from_len); 
    } 
} 

到FineDiff ::类出现以相同的顺序

用法:

你可以玩的是
include 'finediff.php'; 

$from_text = "PHP FPM is a popular general-purpose scripting language that is especially suited to web development."; 
$to_text = "Fast, flexible and pragmatic, PHP FPM powers everything from your blog to the most popular websites in the world"; 

$opcodes = FineDiff::getDiffOpcodes($from_text, $to_text, FineDiff::wordDelimiters); 

FineDiff::renderCommonsFromOpcodes($from_text, $opcodes); 

print_r(FineDiff::$commons); 

/* 
Array 
(
    [0] => PHP FPM 
    [1] => popular 
) 
*/ 
+0

我认为这不是我正在寻找的地方。这是关于新线和调整的权利?内容不相似?如果有一个图书馆重复的内容,它会很好.. – Silver

+0

不,这个库是关于文本的差异,看看[这个演示](http://www.raymondhill.net/finediff/viewdiff-ex.php) 。在稍微玩了一下lib之后,你可以很容易地找到相似的文本。如果您按照相同的顺序查找单词/短语,上述更新可能适用于您。 – Peavey

0

一种方法使用array_intersect其中两个阵列从要比较,然后用一个字符串替换功能来突出常用词的两个字符串产生。

$str1='PHP is a popular general-purpose scripting language that is especially suited to web development.'; 
$str2='Fast, flexible and pragmatic, PHP powers everything from your blog to the most popular websites in the world.'; 

$a1=explode(' ',$str1); 
$a2=explode(' ',$str2); 

function longenough($word){ 
    return strlen($word) > 3; 
} 

$a1=array_filter($a1,'longenough'); 
$a2=array_filter($a2,'longenough'); 

$common=array_intersect($a1, $a2); 

foreach($common as $word){ 
    $str2=preg_replace("@($word)@i",'<span style="color:red">$1</span>', $str2); 
} 

echo $str2; 
+0

谢谢,到目前为止,这是工作正常。但问题是我想匹配更多的单词。突出显示一个单词并不是我想要只突出显示多于两个单词的问题。对此有何建议? – Silver

+0

我会仔细考虑一下 – RamRaider