PHP 2 个字符串之间不区分大小写的单词数
PHP case insensitive count of words common between 2 strings
我正在尝试像这样在 php 中获取 2 段文本...
"A cat jumped over the hat"
"The mad hatter jumped over his cat"
并得到这样的结果...
the
cat
jumped
over
(即字符串之间的常用词,其中不包括帽子,因为它是第二个字符串中另一个词的一部分)
我找到了一堆示例来帮助计算 1 个字符串在另一个字符串中的出现次数,但这最终会给我带来 "hatter" 问题,所以我猜我需要将两个字符串标记为单词-列出并以某种方式进行一对一比较。
努力想出一种有效的方法来实现这一目标,尽管如此感谢任何关于正确方法的想法。谢谢!
对于这个问题,我会使用 explode
将每个字符串分成单词,然后为每个字符串创建一个数组,其中键是单词,值都是 true
。然后,您可以获取其中一个数组,遍历其键,并检查它们是否存在于另一个数组中。
这是使用
的单行
<?php
$str1 = "A cat jumped over the hat";
$str2 = "The mad hatter jumped over his cat";
print_r(array_intersect(array_map("strtolower", explode(' ',$str1)), array_map("strtolower", explode(' ',$str2))));
此输出结果:
Array
(
[1] => cat
[2] => jumped
[3] => over
[4] => the
)
我正在尝试像这样在 php 中获取 2 段文本...
"A cat jumped over the hat"
"The mad hatter jumped over his cat"
并得到这样的结果...
the
cat
jumped
over
(即字符串之间的常用词,其中不包括帽子,因为它是第二个字符串中另一个词的一部分)
我找到了一堆示例来帮助计算 1 个字符串在另一个字符串中的出现次数,但这最终会给我带来 "hatter" 问题,所以我猜我需要将两个字符串标记为单词-列出并以某种方式进行一对一比较。
努力想出一种有效的方法来实现这一目标,尽管如此感谢任何关于正确方法的想法。谢谢!
对于这个问题,我会使用 explode
将每个字符串分成单词,然后为每个字符串创建一个数组,其中键是单词,值都是 true
。然后,您可以获取其中一个数组,遍历其键,并检查它们是否存在于另一个数组中。
这是使用
的单行<?php
$str1 = "A cat jumped over the hat";
$str2 = "The mad hatter jumped over his cat";
print_r(array_intersect(array_map("strtolower", explode(' ',$str1)), array_map("strtolower", explode(' ',$str2))));
此输出结果:
Array
(
[1] => cat
[2] => jumped
[3] => over
[4] => the
)