如何搜索数组中是否存在字符串中的关键字?

时间:2016-10-10 19:22:25

标签: php

我还有一个最多200个字符的字符串,一个包含4000个元素的数组。数组中的每个元素都是不同的,最多可包含3个单词。

我想获得我的字符串中存在的所有关键字。

例如:

$ str ="这是我的测试字符串。请复制此字符串。&#34 ;;

$ arr = ['是','我的测试','测试字符串','字符串'];

所以,我应该得到结果,我的测试,测试字符串,从数组中找到的字符串关键字。

1 个答案:

答案 0 :(得分:0)

你可以这样做:

<?php

$str = "This is my test string. Please copy this strings.";
$arr = ['is', 'my test', 'test string', 'strings'];
$results = [];

foreach($arr as $stringToEvaluate){

  // If the $stringToEvaluate is found in $str
  // then you push it to the $results array

  if(strpos($str, $stringToEvaluate) !== false){
    $results[] = $stringToEvaluate;
  }

}

print_r($results);