简体   繁体   中英

Compare two string and display number of mismatching words from string

I know there are many techniques and methods to comparing two Strings , and find out if two Strings are equal or not. I want to do something like this:

Var Str1 = "Hello How are you?";
var Str2 = "Hello I am ravi.";

To compare str2 with str1 and display the number count of mismatching words. Both strings contain 4 words each. It should display you missed three words from str1 .

I have one web page (web task) where a user needs to listen an audio and transcribe it. So I want to know how many words user misses from the transcribed original audio.

This is as simple as converting both the strings to an array and then computing the difference of arrays.

$arr1 = explode(' ', strtolower($str1));
$arr2 = explode(' ', strtolower($str2));
echo 'You missed ' . count(array_diff($arr1, $arr2)) . ' words from str 1';

Use explode to convert the Strings to Arrays and count the difference between the two Arrays :

$Str1 = "Hello How are you?";
$Str2 = "Hello I am ravi";

$st1 = (explode(" ", $Str1));
$st2 = (explode(" ", $Str2));


$result = array_diff($st1, $st2);

echo count($result);

Find and format difference between two strings in PHP

Try This : https://coderwall.com/p/3j2hxq/find-and-format-difference-between-two-strings-in-php

You can trim the chars like ',', '?' in the string. Then trans it to words array, and remove the duplicate one. Last compare the difference between user input arrays and standard arrays.

// parse a string to array
function words($string)
{
    return array_unique(explode(' ', str_replace(['?', '.', ','], '', $string)));
}

dd(array_diff(words($array2), words($array1)));  //here user input array2 is the first parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM