如何检查字符串中是否存在数组元素


How to check if array elements exist in a string

我有一个数组中的单词列表。检查字符串中是否存在这些单词的最快方法是什么?

目前,我正在通过striposforeach循环逐个检查数组元素的存在。我很好奇是否有更快的方法,就像我们使用数组为str_replace所做的那样。

关于您的附加评论,您可以使用 explode(( 或 preg_split(( 将字符串分解为单个单词,然后使用 array_intersect(( 根据针数组检查此数组。所以所有的工作只做一次。

<?php
$haystack = "Hello Houston, we have a problem";
$haystacks = preg_split("/'b/", $haystack);
$needles = array("Chicago", "New York", "Houston");
$intersect = array_intersect($haystacks, $needles);
$count = count($intersect);
var_dump($count, $intersect);

我可以想象array_intersect((非常快。但这取决于你真正想要什么(匹配单词,匹配片段,..(

我的个人功能:

function wordsFound($haystack,$needles) {
    return preg_match('/'b('.implode('|',$needles).')'b/i',$haystack);      
}
//> Usage:
if (wordsFound('string string string',array('words')))

请注意,如果您使用 UTF-8 外来字符串,则需要使用 utf-8 预词边界的相应值更改 ''b

注意2:请务必在$needles中仅输入a-z0-9字符(感谢MonkeyMonkey(,否则您需要在之前preg_quote

注意3:由于i修饰符,此功能不区分大小写

一般来说,

正则表达式比 str_ipos() 等基本字符串函数慢。但我认为这真的取决于情况。如果您确实需要最大性能,我建议您使用真实世界的数据进行一些测试。