在阵列搜索通配符 [英] Wildcards in array search
问题描述
时,可以使用通配符array_search?我想搜索字符串的一部分,然后
像(带星号)
打印$ POS = array_search('abitofastring%',$瓦尔['myArray的']);
未设置($瓦尔['myArray的'] [$ POS]);
时,可以使用具有
array_search
通配符?
块引用>没有,但你可以使用常规的前pressions(支持通配符)和的
preg_grep
功能。例如:
$阵列=爆炸(,,房子,车子,乘船,骑马,游泳池男孩);#删除阵列不包含豪的所有字符串$阵列= preg_grep('〜HO〜我',$阵列,preG_GREP_INVERT);
该数组然后是:
阵列
(
[1] =>汽车
[2] =>船
[4] =>池男孩
)由于它可以是复杂的编写正前pression模式,它可能是方便有您的SQL LIKE模式转换成一个普通的前pression所以这可以更容易地使用一个辅助功能:
$阵列=爆炸(,,房子,车子,乘船,骑马,游泳池男孩);对于何#搜索每个字符串的开头$正则表达式= like_to_regex('豪%');$阵列= preg_grep($正则表达式,$阵列,preG_GREP_INVERT);的print_r($数组);/ **
*转换一个MySQL LIKE模式成PCRE模式
* /
功能like_to_regex($一样,$ = CASESENSITIVE FALSE,$ escapechar ='\\\\')
{
$模式= sprintf的('〜(小于1%$ S)(%1 $ S {2} | %% | _)〜?!',preg_quote(escapechar $));
$令牌= preg_split($模式,$一样,0,preG_SPLIT_DELIM_CAPTURE | preG_SPLIT_NO_EMPTY);
的foreach($标记为&放大器; $令牌)
{
开关($令牌)
{
案例$ escapechar $ escapechar:
$令牌= preg_quote(escapechar $);
打破;
案件 '_':
$令牌='';
打破;
案件 '%':
$令牌='*';
打破;
默认:
$令牌= preg_quote($令牌); }
}
返回的sprintf('〜^%S $〜%s'的,爆('',$令牌),$ CASESENSITIVE?'':'我');
}Is is possible to use wildcards with array_search? I want to search for part of a string and then
something like(with an asterisk)
print $pos = array_search('abitofastring%', $vars['myarray']); unset($vars['myarray'][$pos]);
解决方案Is is possible to use wildcards with
array_search
?No, but you can use regular expressions (which supports wildcards) and the
preg_grep
function.Example:
$array = explode(',', "House,Car,Boat,Horse,Pool Boy"); # remove all strings from array that do not contain "ho" $array = preg_grep('~ho~i', $array, PREG_GREP_INVERT);
The array then is:
Array ( [1] => Car [2] => Boat [4] => Pool Boy )
As it can be complicated to write regular expression patterns, it might be handy to have a helper function that converts your SQL LIKE pattern into a regular expression so this can be more easily used:
$array = explode(',', "House,Car,Boat,Horse,Pool Boy"); # Search for "Ho" at the beginning of each string $regex = like_to_regex('Ho%'); $array = preg_grep($regex, $array, PREG_GREP_INVERT); print_r($array); /** * convert a MySQL LIKE pattern into a pcre pattern */ function like_to_regex($like, $casesensitive = FALSE, $escapechar = '\\') { $pattern = sprintf('~(?<!%1$s)(%1$s{2}|%%|_)~', preg_quote($escapechar)); $tokens = preg_split($pattern, $like, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); foreach($tokens as &$token) { switch($token) { case $escapechar.$escapechar: $token = preg_quote($escapechar); break; case '_': $token = '.'; break; case '%': $token = '.*'; break; default: $token = preg_quote($token); } } return sprintf('~^%s$~%s', implode('', $tokens), $casesensitive ? '':'i'); }
这篇关于在阵列搜索通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!