【问题标题】:how to using Preg_match for array (multiple key)?如何将 Preg_match 用于数组(多键)?
【发布时间】:2020-03-28 09:53:11
【问题描述】:

例如,我有这几个关键字

$word = "word1,word2,word3";

并使用$keyword = explode(",", trim($word)); 减去/分解它 然后我会得到这些$keyword[0] $keyword[1]$keyword[2]

现在,如何使用 preg_match 匹配这些关键字?

$others = "this is example where there is word1"; 

if(preg_match('/($keyword[0]|$keyword[1]|$keyword[2])/i', $others)){
echo "matched";
}

问题是,如果只有2个单词,它将匹配$others中的所有单词。

还有更合适或更简单有效的方法吗?

【问题讨论】:

  • 您需要从数组中初始化正则表达式吗?尝试$rx = '/' . implode("|", array_map(function($i) { return preg_quote(trim($i), "/"); }, explode(",", $word))) . '/i';,然后使用preg_match($rx, $others),参见demo。在两端添加单词边界\b,以仅匹配整个单词。或者,更好的是,(?<!\w) 开头,(?!\w) 结尾。

标签: php arrays string


【解决方案1】:

array_intersect()explode() 一起使用

$word = "word1,word2,word3";

$others = "this is example where there is word1"; 


$wordsArray = explode(',',$word);
$othersArray = explode(' ',$others);
if(count(array_intersect($othersArray,$wordsArray)) > 0){
    echo "matched";
}else{
    echo "not matched";
}

输出:https://3v4l.org/2fiTmhttps://3v4l.org/vIrnh

如果您想要不区分大小写的检查,请使用strtolower():

$wordsArray = explode(',',strtolower($word));
$othersArray = explode(' ',strtolower($others));
if(count(array_intersect($othersArray,$wordsArray)) > 0){

    echo "matched";
}else{
    echo "not matched";
}

输出:https://3v4l.org/tgflb

注意:- 我假设文本($others 变量)单词用空格分隔。

【讨论】:

  • 所以 $othersArray 会爆炸每个单词?如果 $others 句子很长,是否需要很长时间?我的意思是如果 $others 很长,它会影响服务器吗?
  • 不。它需要太-太-太-太…………太长以影响服务器速度。你可以在这里查看:- 3v4l.org/t4XUG/perf#output
猜你喜欢
  • 1970-01-01
  • 2011-08-17
  • 2021-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多