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
[edit] Last updated: Fri, 25 May 2012

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);
?>

参考



preg_last_error> <preg_filter
[edit] Last updated: Fri, 25 May 2012
 
add a note add a note User Contributed Notes preg_grep
keithbluhm at gmail dot com 21-Jan-2010 04:56
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! 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

 
show source | credits | sitemap | contact | advertising | mirror sites