【问题标题】:match any terms in text to a ready list of terms将文本中的任何术语匹配到现成的术语列表
【发布时间】:2019-04-01 11:01:25
【问题描述】:

我有一组术语:

$arr = [
  'black',
  'white and black',
  'lion',
  'fast',
  'zebra',
  'lion is fast',
  'zebra is white'
];

我想根据特定的句子过滤这个数组,例如:

zebra is white and black, and lion is fast

我尝试使用strpos 和一些正则表达式函数,但没有得到预期的结果。我期望的是在列表中获得minimum 的项目数量,这些项目与 IN ORDER 句子的部分匹配,这将是:

[
  'white and black',
  'zebra',
  'lion is fast'
]

这样我可以将结果以匹配句子中的部分分隔为:

\zebra\ is \white and black\, and \lion is fast\

并忽略数组中的其他项目,因为它们不完全匹配。

你能引导我找到正确的方法吗?

【问题讨论】:

  • 请编辑问题以添加您已经尝试过的代码 sn-ps。
  • 这是一个遍历数组项的循环,并试图在句子中'strpos'它们,很明显列表中的其他一些项是匹配的,例如blacklion ...无论如何我都会发布它。
  • 预期输出是什么?您有两个带有lion 的项目都应该在输出中?
  • 我的问题 <<<<<----- 中的预期输出旁边只有箭头,不,只有 lion is fast 应该匹配,因为它是匹配的完整术语,而不是仅 lion

标签: php arrays substring string-matching


【解决方案1】:

按长度对数组进行排序并循环。
当您在字符串中找到数组项时,将其保存到新数组并从字符串中删除子字符串。

在代码的最后你会得到一个匹配项的数组。

$arr = ['black',
'white and black',
'lion',
'fast',
'zebra',
'lion is fast',
'zebra is white'];

$str = "zebra is white and black, and lion is fast";

function sortl($a,$b){
    return strlen($b)-strlen($a);
}

usort($arr,'sortl');

foreach($arr as $s){
    if(strpos($str, $s) !== false){
        $new[] = $s;
        $str = str_replace($s, "", $str);
    }
}

var_dump($new);

输出:

array(3) {
  [0]=>
  string(15) "white and black"
  [1]=>
  string(12) "lion is fast"
  [2]=>
  string(5) "zebra"
}

https://3v4l.org/7iTHC

【讨论】:

  • 这非常聪明,谢谢,有没有办法在我的另一个问题中使用 mySQL 实现这一目标?你介意看看吗:stackoverflow.com/questions/53025596
  • @tinyCoder 我在 MySQL 中没有这方面的技能。
  • Andreas 还是非常感谢你,我最后可以问一下术语数组是否是 2D 并且每个术语都有一个 ID,比如[{id:12323,term:'white and black'}, {}....] 上面的代码是什么样的?
  • id 是唯一的吗?如果是,那么我将使用 array_column 使数组变平。 $arr = array_column($arr, "term", "id"); 这使键 id 和值成为术语。
  • 不,不幸的是它不是唯一的,这就是为什么我没有在我的评论中将它写为 key=>value,多个术语可能具有相同的 ID。如果列表超过 1000 项,我担心现在的性能。
猜你喜欢
  • 1970-01-01
  • 2022-11-24
  • 2014-10-01
  • 1970-01-01
  • 2012-08-23
  • 1970-01-01
  • 1970-01-01
  • 2019-02-11
  • 1970-01-01
相关资源
最近更新 更多