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;
}
?>
preg_grep
(PHP 4, PHP 5)
preg_grep — パターンにマッチする配列の要素を返す
説明
array preg_grep
( string
$pattern
, array $input
[, int $flags = 0
] )
input 配列の要素のうち、
指定した pattern にマッチするものを要素とする配列を返します。
パラメータ
-
pattern -
検索するパターンを表す文字列。
-
input -
入力の配列。
-
flags -
PREG_GREP_INVERTを設定すると、この関数は 与えたpatternにマッチ しない 要素を返します。
返り値
input 配列のキーを使用した配列を返します。
変更履歴
| バージョン | 説明 |
|---|---|
| 4.2.0 |
パラメータ flags が追加されました。
|
| 4.0.4 |
このバージョンより前は、返される配列の添字は
以前のこの挙動がお好みの場合は、返される配列に array_values() を適用し、添字を再設定してください。 |
例
例1 preg_grep() の例
<?php
// すべての浮動小数点数を含む配列要素を返す
$fl_array = preg_grep("/^(\d+)?\.\d+$/", $array);
?>
参考
- PCRE のパターン
- preg_match_all() - 繰り返し正規表現検索を行う
- preg_filter() - 正規表現による検索と置換を行う
- preg_last_error() - 直近の PCRE 正規表現処理のエラーコードを返す
keithbluhm at gmail dot com
21-Jan-2010 04:56
pete dakin at aargh dot doh!
20-Nov-2008 08:24
<?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
02-Sep-2008 03:31
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
