Table of Contents
回复内容:
Home Backend Development PHP Tutorial 字符串函数 - 关于php的levenshtein函数能否给个通俗易懂的解释,手册看不懂!

字符串函数 - 关于php的levenshtein函数能否给个通俗易懂的解释,手册看不懂!

Jun 06, 2016 pm 08:47 PM
php String functions

如题,越详细越好。谢谢了!

<code>levenshtein("Hello World","ello World");
</code>
Copy after login
Copy after login

它只要在第二个参数添加个'H',只作了1个步骤!也当然返回'1'啦!
这个函数还是蛮简单的,可是:

<code>levenshtein("Hello World","ello World",10,20,30);
</code>
Copy after login
Copy after login

第3个参数:插入一个字符的代价。默认是 1。
第4个参数:替换一个字符的代价。默认是 1。
第5个参数:删除一个字符的代价。默认是 1。
它们的意义在哪?
这个例子中它分别填了10,20,30。
然后返回'30'我不懂了!
它指的'代价'是什么意思?
10,20,30它又分别代表什么意思?

<code>levenshtein('aaa','aab',0,1,0);
</code>
Copy after login
Copy after login

这个例子中它只需替换一次就够了,为什么返回的步骤次数是'0'?

回复内容:

如题,越详细越好。谢谢了!

<code>levenshtein("Hello World","ello World");
</code>
Copy after login
Copy after login

它只要在第二个参数添加个'H',只作了1个步骤!也当然返回'1'啦!
这个函数还是蛮简单的,可是:

<code>levenshtein("Hello World","ello World",10,20,30);
</code>
Copy after login
Copy after login

第3个参数:插入一个字符的代价。默认是 1。
第4个参数:替换一个字符的代价。默认是 1。
第5个参数:删除一个字符的代价。默认是 1。
它们的意义在哪?
这个例子中它分别填了10,20,30。
然后返回'30'我不懂了!
它指的'代价'是什么意思?
10,20,30它又分别代表什么意思?

<code>levenshtein('aaa','aab',0,1,0);
</code>
Copy after login
Copy after login

这个例子中它只需替换一次就够了,为什么返回的步骤次数是'0'?

@怡红公子 已经回答的很好了,我想从底层实现上补充一下题主说的levenshtein('aaa','aab',0,1,0);这个例子,为什么会返回0?

PHP底层使用的算法是经典的矩阵方式(稍有改动),即分别将s1s2的每个字符作为矩阵的行(i[0,m])和列(j[0,n]),每个位置按顺序进行两两比较,如果相等则cost=0(因为不需要任何操作),否则cost=1(这个cost=1就是我们不传递后面3个参数时默认操作的cost了);但是,这里矩阵该项M[i,j]的值还不能直接就等于cost,因为要保证前面操作的传递性(比如你在前面插入了1个字符,后面的字符就要跟着往后挪一位;你在前面插删除了2个字符,后面就要跟着往前挪一位),M[i,j]的值等于M[i-1, j]+1, M[i, j-1]+1, M[i-1, j-1]+cost三个值中最小的(3个值分别表示插入、替换、删除的代价,取最小值表示采用操作代价最小的方式)。这样直到计算到项M[m, n]的值,就是我们需要求的“编辑距离”了。(最后我贴出了php底层c代码对应的php实现)

levenshtein('aaa','aab',1,1,1);的计算演示,单元格[3,3]为最终结果:

a a a
0 1 2 3
a 1 0 1 2
a 2 1 0 1
b 3 2 1 1

levenshtein('aaa','aab',0,1,0);的计算演示,单元格[3,3]为最终结果(因为[1,1]=0, 而且插入的cost设置成了0,导致后面M[i, j-1]的结果都是0,而0是最小值,导致最终返回0):

a a a
0 1 2 3
a 1 0 0 0
a 2 0 0 0
b 3 0 0 0

这里可以看出,levenshtein后面传递的3个参数,是对应的插入、替换、删除三种操作的当前代价(即替换上面求项M[i,j]值的时候后面+的1),而从算法角度来说,任何操作的最小代价单位是1,那么如果我们要得到一个“合理”的返回值,就不能传递0值。传递0就可能导致返回一个不合理,或者说没有实际参考价值的结果。当然,这是跟实际采用的算法密切相关的,就本例来说,最佳操作应该是替换(将aab中的b替换为a),但是PHP采用的算法来看,取的是3种操作方式中最小的值,而且要带入传递性,导致最终结果为0。

<code>#php底层c代码对应的php实现
function levenshtein_php($s1, $s2, $cost_ins=1, $cost_rep=1, $cost_del=1){
    $l1 = strlen($s1);
    $l2 = strlen($s2);

    if ($l1 == 0) {
        return $l2 * $cost_ins;
    }
    if ($l2 == 0) {
        return $l1 * $cost_del;
    }

    $p1 = array();
    $p2 = array();

    for ($i2 = 0; $i2 </code>
Copy after login

PS: 实际上有比利用矩阵结构更优的算法,就不在本题展开了。我没太多算法基础,尝试分析,欢迎批评指正!

通俗的来说就是检测两个字符串的相似程度的,一个字符串变成另外一个字符串的步骤越少的话就是越相似。

<code>$a = "levenshtein";
$b = "levenjdslkfjslkdjfklsjdfljsdlfjsldfjlsdjflsdjltein";
$c = "leveshetin";

$r = levenshtein($a, $b); //int(40)
$s = levenshtein($a, $c); //int(3)
</code>
Copy after login

$a变成$b需要在中间增加40个字符,从$a变成$c需要增加2个字符,删除1个字符,所以是3。

所谓的代价就是一次特定操作所占有的 权重/比重,比如你设置了删除字符的代价是30,做1次删除最后返回给你的就是1*30了。通过设置这个参数有助于尽量多做某个操作避免某个操作。至于后面那个,我个人是这样理解的,所谓的替换其实是经过了“删除”和“增加”两个步骤的合体,如果你把增加和删除设置成0的话就相当于禁止做这两个操作了,替换也就无法操作了。如果你随便给增加和删除来个非0值,则总会返回1。当然这都是我的个人想法,如果有不对的话可以提出来指正。

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles