Jump to: navigation, search

Php similar text

From w3cyberlearnings

Contents

PHP function similar_text

This function calculates the similarity between two input strings and return a percentage of the matching between the two input strings.

Syntax similar_text

  • String1: input 1
  • String2: input 2
  • count (optional): assign the percentage of matching to the count variable.
similar_text(string1, string2, count)

Example 1

<?php
echo similar_text("Good","gooD");
?>

Output: two match (oo)

2

Example 2

<?php
echo similar_text("w3cyberlearnings.com","w3cyberlearnings.com");
?>

Output: All characters match (each string contains 20 characters)

20

Example 3

<?php
echo similar_text("aging population","baby learns to talk");
?>

Output

5

Example 4

<?php

$arrayword = array('doggy is another type', 
       'mother leads us', 
       'father cooks for us', 
       'great father is a great cook', 
       'excellent mother');

$count_aa = array();
for ($i = 0; $i < count($arrayword); $i++) {
	$count_aa[$arrayword[$i]] = similar_text($arrayword[$i], 'mother');
}

print_r($count_aa);
?>

Output

Array
(
    [doggy is another type] => 5
    [mother leads us] => 6
    [father cooks for us] => 4
    [great father is a great cook] => 4
    [excellent mother] => 6
)

Example 5:return percentage of match

<?php
similar_text("aging population","baby learns to talk",$match);
echo $match;
?>

Output

28.571428571429

Example 6

<?php

$arrayword = array('doggy is another type',
     'mother leads us', 
     'father cooks for us', 
     'great father is a great cook', 
     'excellent mother');
$count_aa = array();
for ($i = 0; $i < count($arrayword); $i++) {
	similar_text($arrayword[$i], 'mother', $percentage);
	$count_aa[$arrayword[$i]] = $percentage;
}

print_r($count_aa);
?>

Output

Array
(
    [doggy is another type] => 37.037037037037
    [mother leads us] => 57.142857142857
    [father cooks for us] => 32
    [great father is a great cook] => 23.529411764706
    [excellent mother] => 54.545454545455
)

Related Functions


Navigation
Web
SQL
MISC
References