Home  >  Article  >  php教程  >  使用PHP similar text计算两个字符串相似度,similartext

使用PHP similar text计算两个字符串相似度,similartext

WBOY
WBOYOriginal
2016-06-13 08:51:301299browse

使用PHP similar text计算两个字符串相似度,similartext

在网站开发中,我们经常使用php similar text 计算两个字符串相似度;

1,similar_text的用法

    如果我想计算"ly89cn"和"ly89"的相似程度,有两种表示方法

复制代码 代码如下:
echo similar_text('ly89cn', 'ly89');

     这样输出4,因为他们有4个字符相等

复制代码 代码如下:
similar_text('ly89cn', 'ly89', $percent);
echo $percent;  

这样输出80,$percent代表百分比,说明他们有80%的相似程度

    当然也可以比较两个中文字符,比如“王业楼的个人博客”和“王业楼”

复制代码 代码如下:
echo similar_text('王业楼的个人博客', '王业楼');

    这样输出9,表示他们的9个字节数相等

复制代码 代码如下:
similar_text('王业楼的个人博客', '王业楼', $percent);
echo $percent;

     输出54.545454545455,注意中文字符可能不大准确!

PHP similar_text() 函数

实例

计算两个字符串的相似度,并返回匹配字符的数目:

复制代码 代码如下:
echo similar_text("Hello World","Hello Shanghai");
?>

运行实例

定义和用法

similar_text() 函数计算两个字符串的相似度。

该函数也能计算两个字符串的百分比相似度。

注释:levenshtein() 函数比 similar_text() 函数更快。不过,similar_text() 函数通过更少的必需修改次数提供更精确的结果。

语法

复制代码 代码如下:
similar_text(string1,string2,percent)

参数 描述
string1 必需。规定要比较的第一个字符串。
string2 必需。规定要比较的第二个字符串。
percent 可选。规定供存储百分比相似度的变量名。

技术细节

 

返回值: 返回两个字符串的匹配字符的数目。
PHP 版本: 4+

更多实例

例子 1

计算两个字符串之间的百分比相似度:

复制代码 代码如下:
similar_text("Hello World","Hello Shanghai",$percent);
echo $percent. "%";
?>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn