查找字符串中数组值的首次出现


Find first occurance of array value in a string

我有一个值数组,所有值都包含一个单词,我希望能够找到字符串中最先找到的值。

$materials = array("cotton","silk","polyester","denim","wool");
$string1 = "The fabric composition of this jacket is 100% cotton (body) and 65% polyester / 35% cotton (lining)";
$string2 = "The jeans are made from denim with cotton pockets";

因此,对于$string1,我想说它首先发现了"棉花"作为材料,而对于$strig2,我想它说它首先找到了"牛仔"。

你知道这样做的方法吗?我最初看到的是foreach循环,但它会按照数组的顺序进行,这意味着它也会为两个字符串带回"棉花",因为这是数组中的第一个:

foreach ($materials as $material) {
    if (stripos($string1, $material) !== FALSE) {
        $product_material1 = $material;
        break;
    }
}
$materials = array("cotton","silk","polyester","denim","wool");
$string1 = "The fabric composition of this jacket is 100% cotton (body) and 65% polyester / 35% cotton (lining)";
$string2 = "The jeans are made from denim with cotton pockets";
$firstMatch = array_shift(array_intersect(str_word_count($string1, 1), $materials));
var_dump($firstMatch);
$firstMatch = array_shift(array_intersect(str_word_count($string2, 1), $materials));
var_dump($firstMatch);

如果没有匹配项,您将获得null

注意它是区分大小写的

我喜欢Mark Baker的解决方案,因为我喜欢一行代码,但这里有另一个包含正则表达式和辅助函数的解决方案。

function findFirst($haystack, $needles) {
    if (preg_match('/'.implode('|', $needles).'/', $haystack, $matches)) {
        return $matches[0];
    }
    return null;
}
$first1 = findFirst($string1, $materials);
var_dump($first1);
$first2 = findFirst($string2, $materials);
var_dump($first2);