This function returns matching words array from two texts or returns false in case of not matching any words.

<?php
function strings_intersect_words($str1,$str2){
    $str1 = trim($str1);
    $str2 = trim($str2);
 
    $str1_words = explode(" ",$str1);
    $str2_words = explode(" ",$str2);
 
    $str1_words = array_unique($str1_words);
    $str2_words = array_unique($str2_words);
 
    $intersect_words = array();
 
    foreach($str1_words as $str1_word){
        if(array_search($str1_word,$str2_words)!==false && trim($str1_word)!=""){
            $intersect_words[] = $str1_word;
        }
    }
 
    if(empty($intersect_words)){
        return false;
    }
 
    return $intersect_words;
}
 
$str1 = "I am Ruben Sargsyan from Armenia. I am a web developer.";
$str2 = "http://rubensargsyan.com is a web developer Ruben Sargsyan's personal website.";
 
$intersect_words = strings_intersect_words($str1,$str2);
 
print_r($intersect_words);
?>

Output:

Array ( [0] => Ruben [1] => a [2] => web )

Share

Leave a Reply

Info