- preg_grep
- Parameters
- Return Values
- Errors/Exceptions
- Examples
- See Also
- preg_grep
- Список параметров
- Возвращаемые значения
- Ошибки
- Примеры
- Смотрите также
- User Contributed Notes 4 notes
- preg_grep
- Parameters
- Return Values
- Errors/Exceptions
- Examples
- See Also
- PHP preg_grep() Function
- Syntax
- Parameter Values
- Technical Details
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
preg_grep
Возвращает массив, состоящий из элементов array массива, соответствующих заданному pattern .
Parameters
Шаблон для поиска,как строка.
Если установлено значение PREG_GREP_INVERT , эта функция возвращает элементы входного массива, которые не соответствуют заданному pattern .
Return Values
Возвращает массив, проиндексированный с использованием ключей из array массива, или false в случае ошибки.
Errors/Exceptions
Если переданный шаблон регулярного выражения не компилируется в допустимое регулярное выражение, E_WARNING .
Examples
Пример # 1 preg_grep () Пример
// return all array elements // containing floating point numbers $fl_array = preg_grep("/^(\d+)?\.\d+$/", $array); ?>
See Also
- PCRE Patterns
- preg_quote () — Цитирует символы регулярного выражения
- preg_match_all () — Выполняет поиск глобального регулярного выражения
- preg_filter () — Выполняет поиск и замену регулярного выражения
- preg_last_error () — Возвращает код ошибки последнего выполнения регулярного выражения PCRE
PHP 8.2
(PHP 5 5.3.0,7,8)preg_filter Выполните поиск и замену по регулярному выражению preg_filter()идентичен preg_replace(),за исключением того,что он возвращает только значение
(PHP 5 5.2.0,7,8)preg_last_error Возвращает код выполнения PCRE regex Возвращает код ошибки последнего выполнения PCRE regex.
(PHP 8)preg_last_error_msg Возвращает сообщение о выполнении PCRE regex Возвращает сообщение об ошибке последнего выполнения PCRE regex.
preg_grep
Возвращает массив, состоящий из элементов входящего массива array , которые соответствуют заданному шаблону pattern .
Список параметров
Искомый шаблон в виде строки.
В случае, если установлен в PREG_GREP_INVERT , функция preg_grep() возвращает те элементы массива, которые не соответствуют заданному шаблону pattern .
Возвращаемые значения
Возвращает массив, индексированный ключами из массива array или false в случае возникновения ошибки.
Ошибки
Если переданный шаблон регулярного выражения не компилируется в допустимое регулярное выражение, выдаётся ошибка уровня E_WARNING .
Примеры
Пример #1 Пример использования preg_grep()
// Возвращает все элементы массива,
// содержащие числа с плавающей точкой
$fl_array = preg_grep ( «/^(\d+)?\.\d+$/» , $array );
?>?php
Смотрите также
- Регулярные выражения PCRE
- preg_quote() — Экранирует символы в регулярных выражениях
- preg_match_all() — Выполняет глобальный поиск шаблона в строке
- preg_filter() — Производит поиск и замену по регулярному выражению
- preg_last_error() — Возвращает код ошибки выполнения последнего регулярного выражения PCRE
User Contributed Notes 4 notes
A shorter way to run a match on the array’s keys rather than the values:
function preg_grep_keys ( $pattern , $input , $flags = 0 ) return array_intersect_key ( $input , array_flip ( preg_grep ( $pattern , array_keys ( $input ), $flags )));
>
?>
Run a match on the array’s keys rather than the values:
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 ;
>
This may be obvious to most experienced developers,but just in case its not,when using preg_grep to check for whitelisted items ,one must be very careful to explicitly define the regex boundaries or it will fail
$whitelist = [ «home» , «dashboard» , «profile» , «group» ];
$possibleUserInputs = [ «homd» , «hom» , «ashboard» , «settings» , «group» ];
foreach( $possibleUserInputs as $input )
if( preg_grep ( «/ $input /i» , $whitelist )
echo $input . » whitelisted» ;
>else echo $input . » flawed» ;
>
homd flawed
hom whitelisted
ashboard whitelisted
settings flawed
group whitelisted
I think this is because if boundaries are not explicitly defined,preg_grep looks for any instance of the substring in the whole array and returns true if found.This is not what we want,so boundaries must be defined.
foreach( $possibleUserInputs as $input )
if( preg_grep ( «/^ $input $/i» , $whitelist )
echo $input . » whitelisted» ;
>else echo $input . » flawed» ;
>
>
?>
this results in:
homd flawed
hom flawed
ashboard flawed
settings flawed
group whitelisted
in_array() will also give the latter results but will require few tweaks if say,the search is to be case insensitive,which is always the case 70% of the time
An even shorter way to run a match on the array’s keys rather than the values:
function preg_grep_keys ( $pattern , $input , $flags = 0 ) return array_flip ( preg_grep ( $pattern , array_flip ( $input ), $flags ) );
>
?>
- Функции PCRE
- preg_filter
- preg_grep
- preg_last_error_msg
- preg_last_error
- preg_match_all
- preg_match
- preg_quote
- preg_replace_callback_array
- preg_replace_callback
- preg_replace
- preg_split
preg_grep
Returns the array consisting of the elements of the array array that match the given pattern .
Parameters
The pattern to search for, as a string.
If set to PREG_GREP_INVERT , this function returns the elements of the input array that do not match the given pattern .
Return Values
Returns an array indexed using the keys from the array array, or false on failure.
Errors/Exceptions
If the regex pattern passed does not compile to a valid regex, an E_WARNING is emitted.
Examples
Example #1 preg_grep() example
// return all array elements
// containing floating point numbers
$fl_array = preg_grep ( «/^(\d+)?\.\d+$/» , $array );
?>?phpSee Also
- PCRE Patterns
- preg_quote() — Quote regular expression characters
- preg_match_all() — Perform a global regular expression match
- preg_filter() — Perform a regular expression search and replace
- preg_last_error() — Returns the error code of the last PCRE regex execution
- PCRE Functions
- preg_filter
- preg_grep
- preg_last_error_msg
- preg_last_error
- preg_match_all
- preg_match
- preg_quote
- preg_replace_callback_array
- preg_replace_callback
- preg_replace
- preg_split
PHP preg_grep() Function
The preg_grep() function returns an array containing only elements from the input that match the given pattern.
Syntax
Parameter Values
Parameter Description pattern Required. Contains a regular expression indicating what to search for input Required. An array of strings flags Optional. There is only one flag for this function. Passing the constant PREG_GREP_INVERT will make the function return only items that do not match the pattern. Technical Details
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.