How to find common words in two strings with PHP

2 Answers

0 votes
function extractWords($s) {
    $stopWords = array('i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', 
    'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', 'she', 'her', 
    'hers', 'herself', 'it', 'its', 'itself', 'they', 'them', 'their', 'theirs', 'themselves', 
    'what', 'which', 'who', 'whom', 'this', 'that', 'these', 'those', 'am', 'is', 'are', 'was', 
    'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', 'did', 'doing', 
    'a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', 'at', 
    'by', 'for', 'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 
    'after', 'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 
    'under', 'again', 'further', 'then', 'once', 'here', 'there', 'when', 'where', 'why', 
    'how', 'all', 'any', 'both', 'each', 'few', 'more', 'most', 'other', 'some', 'such', 'no', 
    'nor', 'not', 'only', 'own', 'same', 'so', 'than', 'too', 'very', 's', 't', 'can', 
    'will', 'just', 'don', 'should', 'now', 'means');
     
    $s = strtolower($s); 
    $s = trim($s); 
    // remove all chars except a-zA-Z
    $s = preg_replace('/[^a-zA-Z]/', ' ', $s); 
    // Remove multiple whitespace 
    $s = preg_replace('/\s\s+/i', ' ', $s); 
 
    preg_match_all('/\b.*?\b/i', $s, $words);
    $words = $words[0];
 
    // Get only words that are not stop words with length > 2
    foreach ($words as $key=>$val) {
        if ($val == '' || in_array(strtolower($val), $stopWords) || strlen($val) <= 2) {
            unset($words[$key]);
        }
    }   
    // Remove duplicate words and count word occurrences
    $thewords = array();
    if (is_array($words)) {
        foreach ($words as $key => $val) {
            if (isset($thewords[$val]) ) {
                $thewords[$val]++;
            } else {
                $thewords[$val] = 1;
            }
        }
    }
    arsort($thewords);

    return $thewords;
}

$s1 = "What It Means to Be a Microsoft Certified partner?" . " arr1";
$s2 = "A Microsoft Gold-Certified partner is a company that 
       has agreed to collaborate and establish a close working 
       relationship with Microsoft. Having that title means 
       the company who applied itself has earned the highest 
       standards of Microsoft's widely-recognized partnership program." . " array2";

$words = extractWords($s1);
$s = implode(', ', array_keys($words));
$array1 =  explode(" ", $s);

$words = extractWords($s2);
$s = implode(', ', array_keys($words));
$array2 =  explode(" ", $s);

$result = array_intersect($array1, $array2);
print_r($result);



/*
run:

Array
(
    [0] => microsoft,
    [1] => certified,
    [2] => partner,
)

*/

 



answered Sep 29, 2020 by avibootz
edited Sep 29, 2020 by avibootz
0 votes
/**
 * Find common words between two strings.
 *
 * This function:
 * - Normalizes both strings (lowercase, trimmed)
 * - Splits them into word arrays
 * - Removes empty entries
 * - Uses array operations to efficiently compute intersections
 */
function findCommonWords(string $a, string $b): array
{
    // Normalize input: convert to lowercase so comparisons are consistent
    $a = strtolower($a);
    $b = strtolower($b);

    // Split strings into words using preg_split to handle punctuation and spacing
    // The pattern splits on any non-letter character
    $wordsA = preg_split('/[^a-z]+/', $a, -1, PREG_SPLIT_NO_EMPTY);
    $wordsB = preg_split('/[^a-z]+/', $b, -1, PREG_SPLIT_NO_EMPTY);

    // Compute intersection; array_intersect preserves order from the first array
    $common = array_intersect($wordsA, $wordsB);

    // Remove duplicates while preserving order
    return array_values(array_unique($common));
}

/**
 * Example usage
 */
$string1 = "The quick brown fox jumps over the lazy dog.";
$string2 = "A lazy dog sleeps while the quick fox runs away.";

// Get common words
$commonWords = findCommonWords($string1, $string2);

// Print result
echo "Common words:\n";
print_r($commonWords);



/*
run:

Common words:
Array
(
    [0] => the
    [1] => quick
    [2] => fox
    [3] => lazy
    [4] => dog
)


*/

 



answered Sep 11 by avibootz
edited Sep 11 by avibootz
...