问题描述
我有一个值数组,所有值都包含一个单词,我希望能够找到首先在字符串中找到的那些值。
I've got an array of values, all containing one word, and I'd like to be able to find which of those values is found first 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,我想说它首先找到棉作为材质和$ string2,我想说它首先找到了牛仔布。
So for the $string1, I'd like it to say that it found 'cotton' first as the material and for the $string2 I'd like it to say that it found 'denim' first.
您知道这样做的方法吗?我本来是在查看foreach循环的,但它会按数组的顺序排列,这意味着它将同时为这两个字符串带来棉布,因为这是数组中的第一个:
Do you know a way of doing this? I was originally looking at a foreach loop but it would go in order of the array meaning it would also bring 'cotton' back for both strings as that's the first one in the array:
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
If there's no match, you'll get a null
请注意,它区分大小写
这篇关于查找字符串中数组值的首次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!