我正在搜索数组中的特定值,我想知道我是否可以搜索以查看该值包含我搜索的内容,而不一定是完全匹配
所以..
$a = array("red", "reddish", "re", "red diamond");
这只会给我一把钥匙
$red = array_keys($a, "red");
如果我想要包含单词red的所有键,该怎么办?所以我想" red"," reddish"和"红钻"
或者说我想要0, 1, 3
答案 0 :(得分:1)
使用preg_grep
:
$a = array("red", "reddish", "re", "red diamond");
$red = array_keys(preg_grep("/red/", $a));
print_r($red);
上面的代码为您提供了$a
中包含字符串"red"
的所有值的键。如果您需要$a
中以字符串"red"
开头的所有值的键,只需将正则表达式从"/red/"
更改为"/^red/"
即可。
答案 1 :(得分:1)
你可以这样做>的 Live Demonstration 强>
Red
// Create a function to filter anything 'red'
function red($var) {
if(strpos($var, 'red') === false) {
// If array item does not contain red, filter it out by returning false
return false;
} else {
// If array item contains 'red', then keep the item
return $var;
}
}
// Set the array (as per your question)
$array = array("red", "reddish", "re", "red diamond");
// This line executes the function red() passing the array to it.
$newarray = array_filter($array, 'red');
// Dump the results
var_export( array_keys($newarray) );
使用array_filter()
或array_map()
可让开发人员更好地控制数组中的快速循环,以过滤和执行其他代码。上述功能旨在满足您的要求,但它可能会像您想要的那样复杂。
如果您想设置值' red'在它内部更具动态性,你可以做类似以下的事情:
// Set the array (as per your question)
$array = array("red", "reddish", "re", "red diamond");
// Set the text you want to filter for
$color_filter = 'red';
// This line executes the function red() passing the array to it.
$newarray = array_filter($array, 'dofilter');
// Dump the results
var_export( array_keys($newarray) );
// Create a function to filter anything 'red'
function dofilter($var) {
global $color_filter;
if(strpos($var, $color_filter) === false) {
// If array item does not contain $color_filter (value), filter it out by returning false
return false;
} else {
// If array item contains $color_filter (value), then keep the item
return $var;
}
}
答案 2 :(得分:0)
$a = array("red", "reddish", "re", "red diamond");
function find_matches( $search, $array )
{
$keys = array();
foreach( $array as $key => $val )
{
if( strpos( $val, $search ) !== false )
$keys[] = $key;
}
return $keys;
}