Home  >  Article  >  Backend Development  >  PHP calculates the similarity function similar_text() between two strings

PHP calculates the similarity function similar_text() between two strings

黄舟
黄舟Original
2017-11-02 14:28:342407browse

Example

Calculate the similarity of two strings and return the number of matching characters:

<?php
echo similar_text("Hello World","Hello Peter");
?>

Definition and usage

similar_text() function calculates two strings similarity.

This function can also calculate the percentage similarity of two strings.

Note: levenshtein() function is faster than similar_text() function. However, the similar_text() function provides more accurate results with fewer modifications required.

Syntax

similar_text(string1,string2,percent)

Parameter Description

string1 Required. Specifies the first string to compare. ​

string2 Required. Specifies the second string to be compared.

percent Optional. Specifies the variable name used to store percent similarity.

Technical details

Return value: Returns the number of matching characters in the two strings.

PHP version: 4+

More examples

Example 1

Calculate the percentage similarity of two strings:

<?php
similar_text("Hello World","Hello Peter",$percent);
echo $percent;
?>

PHP has a function similar_text() that calculates the similarity of two strings, and you can get a percentage to express the similarity of the two strings. The effect is as follows:

similar_text(&#39;aaaa&#39;, &#39;aaaa&#39;, $percent); 
var_dump($percent); 
//float(100) 
similar_text(&#39;aaaa&#39;, &#39;aaaabbbb&#39;, $percent); 
var_dump($percent); 
//float(66.666666666667) 
similar_text(&#39;abcdef&#39;, &#39;aabcdefg&#39;, $percent); 
var_dump($percent); 
//float(85.714285714286)

Using this function, you can use it to perform fuzzy search functions, or other functions that require fuzzy matching. Recently, I have involved this function in the feature matching step in the research on verification code recognition.

The above is the detailed content of PHP calculates the similarity function similar_text() between two strings. For more information, please follow other related articles on the PHP Chinese website!

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