downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

preg_last_error> <preg_filter
Last updated: Fri, 06 Nov 2009

view this page in

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

このバージョンより前は、返される配列の添字は input 配列のキーにかかわらず設定されていました。

以前のこの挙動がお好みの場合は、返される配列に array_values() を適用し、添字を再設定してください。

例1 preg_grep() の例

<?php
// すべての浮動小数点数を含む配列要素を返す
$fl_array preg_grep("/^(\d+)?\.\d+$/"$array);
?>



add a note add a note User Contributed Notes
preg_grep
pete dakin at aargh dot doh!
20-Nov-2008 03: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 08: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

preg_last_error> <preg_filter
Last updated: Fri, 06 Nov 2009
 
 
show source | credits | sitemap | contact | advertising | mirror sites