(PHP 4, PHP 5)
preg_grep — 返回匹配模式的数组条目
$pattern
, array $input
[, int $flags
= 0
] )
返回给定数组input
中与模式pattern
匹配的元素组成的数组.
pattern
要搜索的模式, 字符串形式.
input
输入数组.
flags
如果设置为PREG_GREP_INVERT
, 这个函数返回输入数组中与
给定模式pattern
不匹配的元素组成的数组.
返回使用input
中key做索引的数组.
版本 | 说明 |
---|---|
4.2.0 |
增加了参数flags .
|
4.0.4 |
在此版本之前, 返回数组的索引与 如果你想仿照这种旧有的行为, 在返回数组上使用 array_values()重建索引. |
Example #1 preg_grep() 示例
<?php
// 返回所有包含浮点数的元素
$fl_array = preg_grep("/^(\d+)?\.\d+$/", $array);
?>
Daniel Klein (2013-03-14 22:54:09)
A shorter way to run a match on the array's keys rather than the values:
<?php
function preg_grep_keys($pattern, $input, $flags = 0) {
return array_intersect_key($input, array_flip(preg_grep($pattern, array_keys($input), $flags)));
}
?>
keithbluhm at gmail dot com (2010-01-21 15:56:12)
Run a match on the array's keys rather than the values:
<?php
function preg_grep_keys( $pattern, $input, $flags = 0 )
{
$keys = preg_grep( $pattern, array_keys( $input ), $flags );
$vals = array();
foreach ( $keys as $key )
{
$vals[$key] = $input[$key];
}
return $vals;
}
?>
pete dakin at aargh dot doh! (2008-11-20 07:24:18)
<?php
/**
* Return the element key for a found pattern in an array
*
* @param String pattern
* @param Array input
* @return mixed
*/
function preg_array_key( $sPattern, $aInput ){
return key( preg_grep( $sPattern, $aInput ) );
}
?>
brian at cristina dot org (2008-09-02 13:31:53)
I don't see it mentioned here but you can invert your match to only return array entries where the search values IS NOT found. The format for it is...
<?php
$nomatch = preg_grep("/{$keyword}/i",$array,PREG_GREP_INVERT);
?>
Notice the PREG_GREP_INVERT.
That will result in an array ($nomatch) that contains all entries of $array where $keyword IS NOT found.
Hope that helps!
-b