preg_grep

(PHP 4, PHP 5)

preg_grep --  返回与模式匹配的数组单元

说明

array preg_grep ( string pattern, array input )

preg_grep() 返回一个数组,其中包括了 input 数组中与给定的 pattern 模式相匹配的单元。

自 PHP 4.0.4 起,preg_grep() 返回的结果使用从输入数组来的键名进行索引。如果不希望这样的结果,用 array_values()preg_grep() 返回的结果重新索引。

例子 1. preg_grep() 例子

<?php
// return all array elements
// containing floating point numbers
$fl_array = preg_grep ("/^(\d+)?\.\d+$/", $array);
?>


add a note add a note User Contributed Notes
tobyf at web dot de
24-May-2006 03:39
For older PHP versions (> 4.2.0) you can use this function:

<?php
function c_preg_grep($pattern,&$array,$flag=false)
{
   if (
$flag != PREG_GREP_INVERT)
   {
       return
preg_grep($pattern,$array);
   }
   else
   {
      
$remove = preg_grep($pattern,$array);
       return
array_diff($array,$remove);
   }
}
?>
ak85 at yandex dot ru
03-Aug-2005 01:28
If U wanna find substring without word "BADWORD" U can use this expression:
/((?:(?!BADWORD).)*)/s
For example:
preg_match_all('/<b>((?:(?!</b>).)*)</b>/is',$string,$matches);
// U can find at the $matches substrings of $string between '<b>' and '</b>' without the same tag '</b>'

// Was found at O'Reilly Rerl Cookbook Russian Edition 2001
erik dot dobecky at NOSPAM dot fi-us dot com
30-Apr-2005 12:15
A useful way that we have developed filters against SQL injection attempts is to preg_grep the $_REQUEST global with the following regular expression (regex):

   '/[\'")]* *[oO][rR] *.*(.)(.) *= *\\2(?:--)?\\1?/'

which is used simply as:
<?php
$SQLInjectionRegex
= '/[\'")]* *[oO][rR] *.*(.)(.) *= *\\2(?:--)?\\1?/';
$suspiciousQueryItems = preg_grep($SQLInjectionRegex, $_REQUEST);
?>

which matches any of the following (case insensitive, a=any char) strings (entirely):

' or 1=1--
" or 1=1--
or 1=1--
' or 'a'='a
" or "a"="a
') or ('a'='a
Matt AKA Junkie
06-Jun-2004 03:05
To grep using preg_* from a string instead of an array, use preg_match_all().
zac at slac dot stanford dot edu
27-Jul-2002 10:02
preg_grep takes a third argument (PREG_GREP_INVERT) which negates the pattern matching behaviour, just like the "-v" flag to the grep command.

EXAMPLE:
$food = array('apple', 'banana', 'squid', 'pear');
$fruits = preg_grep("/squid/", $food, PREG_GREP_INVERT);
echo "Food  "; print_r($food);
echo "Fruit "; print_r($fruits);

RESULTS IN:
Food  Array
(
   [0] => apple
   [1] => banana
   [2] => squid
   [3] => pear
)
Fruit Array
(
   [0] => apple
   [1] => banana
   [3] => pear
)