gpt4 book ai didi

php - 在 php 数组中搜索部分字符串匹配

转载 作者:行者123 更新时间:2023-12-02 12:16:22 37 4
gpt4 key购买 nike

我有一个数组,我想搜索字符串 'green' 。所以在这种情况下它应该返回 $arr[2]

$arr = array(0 => 'blue', 1 => 'red', 2 => 'green string', 3 => 'red');

是否有像 in_array() 这样的预定义函数可以完成这项工作而不是循环遍历并比较每个值?

最佳答案

对于部分匹配,您可以迭代数组并使用字符串搜索函数,如 strpos() .

function array_search_partial($arr, $keyword) {
foreach($arr as $index => $string) {
if (strpos($string, $keyword) !== FALSE)
return $index;
}
}

完全匹配,请使用 in_array()

in_array('green', $arr)

关于php - 在 php 数组中搜索部分字符串匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15944824/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com