Rya*_*n D 5 php arrays string loops preg-grep
这是一个工作脚本,带有一组更好的示例字符串来显示我的意图 -
$strings[] = 'seventy five yards out';
$strings[] = 'sixty yards out';
$strings[] = 'one hundred fifty yards out';
$inputString = 'seventy two yards out';
$inputWords = str_word_count($inputString, 1);
$foundWords = [];
foreach ($strings as $key => $string) {
$stringWords = str_word_count($string, 1);
$wordsCount = array_count_values($stringWords);
$commonWords = array_intersect($inputWords, array_keys($wordsCount));
if (count($commonWords) > 0) {
foreach ($commonWords as $commonWord) {
$foundWords[$key][$commonWord] = $wordsCount[$commonWord];
}
}
}
print_r($foundWords);
Run Code Online (Sandbox Code Playgroud)
如何将它打印出"七十五码外",因为它实际上最接近文本?我正在考虑将字数除以得到一个百分比,但现在认为现在可能有效了..
关键是str_word_count()对每个提供的字符串分别执行 a 。通过这种方式,我们可以将其转换为数组,并且根据您的需要处理数组要简单得多。
array_count_values()计算数组的值,从而得出单词出现的次数。
$strings[] = 'seventy five yards out';
$strings[] = 'sixty yards out';
$strings[] = 'one hundred fifty yards out';
$inputString = 'seventy two yards out';
$inputWords = str_word_count($inputString, 1);
$probabilities = [];
foreach ($strings as $key => $string) {
$stringWords = str_word_count($string, 1);
$wordsCount = array_count_values($stringWords);
$commonWords = array_intersect($inputWords, array_keys($wordsCount));
if (count($commonWords) > 0) {
foreach ($commonWords as $commonWord) {
if (!isset($probabilities[$key])) $probabilities[$key] = 0;
$probabilities[$key] += $wordsCount[$commonWord];
}
$probabilities[$key] /= count($stringWords);
}
}
arsort($probabilities);
echo $strings[key($probabilities)];
Run Code Online (Sandbox Code Playgroud)
输出:
seventy five yards out
Run Code Online (Sandbox Code Playgroud)
概率print_r($probabilities);:
Array
(
[0] => 0.75
[1] => 0.66666666666667
[2] => 0.4
)
Run Code Online (Sandbox Code Playgroud)