查找字符串中与多个数组键匹配的所有单词

问题描述:

I have an array like array("red","blue","azure"...) and i have a string that might contain some of the words. The task is to get array of all the matching colors from the given string.

String example: "Red fox met a blue whale". It should output ["red","blue"]

Give me a starting point to go on with.

Thanks, Martti

我有一个像数组一样的数组(“red”,“blue”,“azure”...... ) code>,我有一个字符串可能包含一些单词。 任务是从给定的字符串中获取所有匹配颜色的数组。 p>

字符串示例:“红狐狸遇到蓝鲸”。 它应输出[“red”,“blue”] p>

给我一​​个起点继续。 p>

谢谢, Martti p> div>

str_word_count() with a format argument of 1 or 2, then an array_intersect().... but watch out for case-sensitivity, force it all to lower case first

$matchWords = array("red","blue","azure");
$sentence = "Red fox met a blue whale";

$result = array_intersect(
    $matchWords,
    str_word_count(strtolower($sentence), 1)
);

var_dump($result);

Demo

If you put all the values that you are looking for into an array, using '|' as a delimiter, you can use this in a regex to match all values.

$valsArray = implode('|',$vals);

preg_match_all('/($valsArray)/',$string,$matches);

var_dump($matches);

Try this

<?php

$array1=array("red","blue","azure") ;
$str="red fox met a blue whale";
$str=explode(" ",$str);

echo $array1[0];
for($i=0;$i<sizeof($array1);$i++){
    
    if (in_array($array1[$i],$str)){
$words[]=$array1[$i];

}

    }
print_r($words)

?>

</div>

EDIT:

I figured out I need it to be more complex. Is it possible to do it like that:

1) Let's find all the colors from the string that are present in the array 2) Translate the colors to other language using another array

original array ["red","blue","green"] translated array ["punane","sinine","roheline"]

So from "Red fox met a blue whale" I need to get ["punane","sinine"]

Thanks, Martti

guys.

This is the code to translate filtered items using matching translated array

  foreach($filteredArray as $key => $value) {
      $myTranslatedColors[] = $translatedArray[$key]; 
    }

Thank you all.