php array match array

preg_match_all

(PHP 4, PHP 5, PHP 7, PHP 8)

preg_match_all — Выполняет глобальный поиск шаблона в строке

Описание

После нахождения первого соответствия последующие поиски будут осуществляться не с начала строки, а от конца последнего найденного вхождения.

Список параметров

Искомый шаблон в виде строки.

Может быть комбинацией следующих флагов (необходимо понимать, что использование PREG_PATTERN_ORDER одновременно с PREG_SET_ORDER бессмысленно): PREG_PATTERN_ORDER

Результат выполнения данного примера:

Результат выполнения данного примера:

PREG_SET_ORDER

Результат выполнения данного примера:

PREG_OFFSET_CAPTURE

Результат выполнения данного примера:

PREG_UNMATCHED_AS_NULL

Если этот флаг передан, несовпадающие подмаски будут представлены значениями null ; в противном случае они отображаются в виде пустых строк ( string ).

Обычно поиск осуществляется слева направо, с начала строки. Дополнительный параметр offset может быть использован для указания альтернативной начальной позиции для поиска.

Возвращаемые значения

Возвращает количество найденных вхождений шаблона (которое может быть и нулём) или false в случае возникновения ошибки.

Список изменений

Примеры

Пример #1 Получение всех телефонных номеров из текста.

Пример #2 Жадный поиск совпадений с HTML-тэгами

// Запись \\2 является примером использования ссылок на подмаски.
// Она означает необходимость соответствия подстроки строке, захваченной
// второй подмаской, в нашем примере это ([\w]+).
// Дополнительный обратный слеш необходим, так как используются двойные кавычки.
$html = «полужирный текстнажми» ;

Результат выполнения данного примера:

Пример #3 Использование именованных подмасок

Результат выполнения данного примера:

Смотрите также

User Contributed Notes 34 notes

if you want to extract all s from a string:

The code that john at mccarthy dot net posted is not necessary. If you want your results grouped by individual match simply use:

array(0 => ‘G1?’, 1 => ‘H2!’),
// 1 => array(0 => ‘G’, 1 => ‘H’),
// 2 => array(0 => ‘1’, 1 => ‘2’),
// 3 => array(0 => ‘?’, 1 => ‘!’))

Источник

Функции для работы с массивами

Содержание

User Contributed Notes 14 notes

A simple trick that can help you to guess what diff/intersect or sort function does by name.

Example: array_diff_assoc, array_intersect_assoc.

Example: array_diff_key, array_intersect_key.

Example: array_diff, array_intersect.

Example: array_udiff_uassoc, array_uintersect_assoc.

This also works with array sort functions:

Example: arsort, asort.

Example: uksort, ksort.

Example: rsort, krsort.

Example: usort, uasort.

?>
Return:
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Cuatro [ 4 ] => Cinco [ 5 ] => Tres [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Tres [ 4 ] => Cuatro [ 5 ] => Cinco [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
?>

Updated code of ‘indioeuropeo’ with option to input string-based keys.

Here is a function to find out the maximum depth of a multidimensional array.

// return depth of given array
// if Array is a string ArrayDepth() will return 0
// usage: int ArrayDepth(array Array)

Short function for making a recursive array copy while cloning objects on the way.

If you need to flattern two-dismensional array with single values assoc subarrays, you could use this function:

to 2g4wx3:
i think better way for this is using JSON, if you have such module in your PHP. See json.org.

to convert JS array to JSON string: arr.toJSONString();
to convert JSON string to PHP array: json_decode($jsonString);

You can also stringify objects, numbers, etc.

Function to pretty print arrays and objects. Detects object recursion and allows setting a maximum depth. Based on arraytostring and u_print_r from the print_r function notes. Should be called like so:

I was looking for an array aggregation function here and ended up writing this one.

Note: This implementation assumes that none of the fields you’re aggregating on contain The ‘@’ symbol.

While PHP has well over three-score array functions, array_rotate is strangely missing as of PHP 5.3. Searching online offered several solutions, but the ones I found have defects such as inefficiently looping through the array or ignoring keys.

Источник

preg_match

(PHP 4, PHP 5, PHP 7, PHP 8)

preg_match — Выполняет проверку на соответствие регулярному выражению

Описание

Список параметров

Искомый шаблон в виде строки.

flags может быть комбинацией следующих флагов: PREG_OFFSET_CAPTURE

Результат выполнения данного примера:

PREG_UNMATCHED_AS_NULL

Если этот флаг передан, несовпадающие подмаски будут представлены значениями null ; в противном случае они отображаются в виде пустых строк ( string ).

Результат выполнения данного примера:

Обычно поиск осуществляется слева направо, с начала строки. Можно использовать дополнительный параметр offset для указания альтернативной начальной позиции для поиска (в байтах).

Результат выполнения данного примера:

В то время как этот пример

Возвращаемые значения

Список изменений

Примеры

Пример #1 Поиск подстроки «php» в тексте

Пример #2 Поиск слова «web» в тексте

Пример #3 Извлечение доменного имени из URL

Результат выполнения данного примера:

Пример #4 Использование именованных подмасок

Результат выполнения данного примера:

Примечания

Смотрите также

User Contributed Notes 51 notes

Regex quick reference
[abc] A single character: a, b or c
[^abc] Any single character but a, b, or c
[a-z] Any single character in the range a-z
[a-zA-Z] Any single character in the range a-z or A-Z
^ Start of line
$ End of line
\A Start of string
\z End of string
. Any single character
\s Any whitespace character
\S Any non-whitespace character
\d Any digit
\D Any non-digit
\w Any word character (letter, number, underscore)
\W Any non-word character
\b Any word boundary character
(. ) Capture everything enclosed
(a|b) a or b
a? Zero or one of a
a* Zero or more of a
a+ One or more of a
a <3>Exactly 3 of a
a <3,>3 or more of a
a <3,6>Between 3 and 6 of a

options: i case insensitive m make dot match newlines x ignore whitespace in regex o perform # <. >substitutions only once

I noticed that in order to deal with UTF-8 texts, without having to recompile php with the PCRE UTF-8 flag enabled, you can just add the following sequence at the start of your pattern: (*UTF8)

for instance : ‘#(*UTF8)[[:alnum:]]#’ will return TRUE for ‘é’ where ‘#[[:alnum:]]#’ will return FALSE

found this very very useful tip after hours of research over the web directly in pcre website right here : http://www.pcre.org/pcre.txt
there are many further informations about UTF-8 support in the lib

hop that will help!

Sometimes its useful to negate a string. The first method which comes to mind to do this is: [^(string)] but this of course won’t work. There is a solution, but it is not very well known. This is the simple piece of code on how a negation of a string is done:

Hope this helps some ppl.

Was working on a site that needed japanese and alphabetic letters and needed to
validate input using preg_match, I tried using \p


Fatal error: Uncaught JSMin_UnterminatedStringException: JSMin: Unterminated String at byte 20: 't work:</p> in /var/www/www-ars1963/data/www/farminfoservice.ru/wp-content/plugins/autoptimize/classes/external/php/jsmin.php:214 Stack trace: #0 /var/www/www-ars1963/data/www/farminfoservice.ru/wp-content/plugins/autoptimize/classes/external/php/jsmin.php(152): JSMin->action(1) #1 /var/www/www-ars1963/data/www/farminfoservice.ru/wp-content/plugins/autoptimize/classes/external/php/jsmin.php(86): JSMin->min() #2 /var/www/www-ars1963/data/www/farminfoservice.ru/wp-content/plugins/autoptimize/classes/autoptimizeSpeedupper.php(38): JSMin::minify('but didn't work...') #3 /var/www/www-ars1963/data/www/farminfoservice.ru/wp-includes/class-wp-hook.php(324): autoptimizeSpeedupper->js_snippetcacher('but didn't work...', '') #4 /var/www/www-ars1963/data/www/farminfoservice.ru/wp-includes/plugin.php(205): WP_Hook->apply_filters('but didn't work...', Array) #5 /var/www/www-ars1963/data/www/farminfoservice.ru/wp-content/plugins/autoptimize/ in /var/www/www-ars1963/data/www/farminfoservice.ru/wp-content/plugins/autoptimize/classes/external/php/jsmin.php on line 214