📜  php 计算两个字符串中匹配的单词 - PHP (1)

📅  最后修改于: 2023-12-03 14:45:26.294000             🧑  作者: Mango

PHP 计算两个字符串中匹配的单词

本文通过 PHP 介绍了计算两个字符串中匹配的单词的方法。算法首先将两个字符串分割成单词数组,然后遍历其中一个数组进行匹配,并返回匹配的结果。

<?php

/**
 * 计算两个字符串中匹配的单词
 *
 * @param string $string1 字符串1
 * @param string $string2 字符串2
 * @return array 匹配的单词数组
 */
function findMatchingWords($string1, $string2) {
    // 将字符串分割成单词数组
    $words1 = str_word_count(strtolower($string1), 1);
    $words2 = str_word_count(strtolower($string2), 1);

    // 构建匹配的单词数组
    $matchingWords = array_intersect($words1, $words2);
    
    return $matchingWords;
}

// 示例用法
$string1 = "This is a sample string.";
$string2 = "This is another string.";

$matchingWords = findMatchingWords($string1, $string2);

echo "匹配的单词:" . implode(", ", $matchingWords);
?>

以上代码的输出结果将显示两个字符串中匹配的单词,例如上述示例输出为:

匹配的单词:this, is, string

这个算法的时间复杂度为 O(n),其中 n 为单词数组的长度。

希望这个代码片段能够帮助你在 PHP 中计算两个字符串中匹配的单词。