我正在一个数组中搜索特定的值,我想知道是否可以搜索以查看该值包含我正在搜索的内容,而不一定是完全匹配的
所以。。
$a = array("red", "reddish", "re", "red diamond");
这只会给我一个密钥
$red = array_keys($a, "red");
如果我想要所有包含单词红色的键,那么我想要"红色"、"红色"answers"红色钻石"
或者我想要0, 1, 3
您可以这样做>现场演示
专门搜索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()
的使用使开发人员能够更好地控制通过数组的快速循环,以过滤和执行其他代码。上面的函数是为满足您的要求而设计的,但它也可以根据您的需要而复杂。
如果您希望将其内部的值"红色"设置为更动态,您可以执行以下操作:
通用搜索方法
// 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;
}
}
使用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/"
即可。
$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;
}