在字符串中查找第一次出现的数组值

时间:2015-03-06 15:49:21

标签: php arrays

我有一系列值,都包含一个单词,我希望能够找到首先在字符串中找到哪些值。

$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,我希望它能说它找到了' cotton'首先作为材料和$ string2我希望它能说它找到了'牛仔布'第一

你知道这样做的方法吗?我原本看着一个foreach循环,但它会按照数组的顺序排列,这意味着它也会带来棉花'返回两个字符串,因为它是数组中的第一个字符串:

foreach ($materials as $material) {
    if (stripos($string1, $material) !== FALSE) {
        $product_material1 = $material;
        break;
    }
}

2 个答案:

答案 0 :(得分:2)

$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

请注意,它区分大小写

答案 1 :(得分:1)

我喜欢Mark Ba​​ker的解决方案,因为我喜欢一个衬垫,但这是另一个带有正则表达式和辅助函数的解决方案。

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);
相关问题