首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP -文本匹配

PHP -文本匹配
EN

Stack Overflow用户
提问于 2015-01-08 18:23:39
回答 1查看 160关注 0票数 1

我目前正在尝试找出两个字符串中匹配的单词的百分比

其想法是,将一个字符串与另一个字符串进行匹配,并获得它们之间的相似度百分比。

我现在有一个粗略的想法,我想知道我是否可以得到一些帮助,这个想法是将每个字符串转换为一个数组,您可以逐个迭代列表,如果匹配,则将1添加到$matches,如果不匹配,则添加0

代码语言:javascript
复制
<?php>
$originalText = "The quick brown fox jumps over the lazy dog";
$comparisonText = "The quick red fox leaps over the sleeping dog";
//to get a count the number of words we are trying to match
$strNum = str_word_count($originalText);

$arroriginalText = explode(" ", $originalText);
$arrcomparisonText = explode(" ", $comparisonText);

//THIS IS WHERE I'M STUCK
//creating some form of a loop to go through the array of strings

if (preg_match("*word from $arroriginalText*, *word from $arrcomparisonText*", $matches)) {
//not fully understanding what to put here
}

//i'm bad at maths
$strNum - $matches = $percentageFind
$percentageFind / $strNum = $decimal
$decimal * 100 = $theAnswer
?>

我不确定我是否已经清楚地表达了我的想法,但如果有任何帮助,我将非常感激。

EN

回答 1

Stack Overflow用户

发布于 2015-01-08 18:27:32

代码语言:javascript
复制
$matches = 0;

if( empty( $arroriginalText ) ) {
  echo 'Empty';
  die();
}

for( $n = 0; $n < count( $arroriginalText ); $n++ ) {
  if( $arrcomparisonText[$n] === $arroriginalText[$n] ) {
     $matches++;
  }
}

$percentage = 100 * $matches / count( $arroriginalText );

或者更好(未测试)

代码语言:javascript
复制
$percentage = count( array_diff( $arroriginalText, $arrcomparisonText ) ) / count( $arroriginalText );
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27837797

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档