= PHP_5_3_0, PHP_7, PHP_8 // preg_grep() - PHP_4, PHP_5, PHP_7, PHP_8 // OFFLINE | preg_last_error_msg() - PHP_8 // OFFLINE | preg_last_error() - PHP_5 >= PHP_5_2_0, PHP_7, PHP_8 // preg_match_all() - PHP_4, PHP_5, PHP_7, PHP_8 // preg_match() - PHP_4, PHP_5, PHP_7, PHP_8 // preg_quote() - PHP_4, PHP_5, PHP_7, PHP_8 // OFFLINE | preg_replace_callback_array() - PHP_7, PHP_8 // preg_replace_callback() - PHP_4 >= PHP_4_0_5, PHP_5, PHP_7, PHP_8 // preg_replace() - PHP_4, PHP_5, PHP_7, PHP_8 // preg_split() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== USING CLASSES (0) // ============================== USING DATA_TYPES (6) // string // array // null // int // false // callable // ============================== END // REQUIREMENTS // ============================== // ============================== BEGIN // PHP_TEXT_PCRE // ============================== ABOUT // PHP Manual / Function Reference / Text Processing / PCRE - Regular Expressions (Perl-Compatible) // URL: https://www.php.net/manual/en/book.pcre.php // ============================== DESCRIPTION // REGULAR_EXPRESSIONS_PERL_COMPATIBLE // // REGULAR_EXPRESSIONS_PERL_COMPATIBLE - BEGIN // Regular Expressions (Perl-Compatible) // // INTRODUCTION // INSTALLING_CONFIGURING // PREDEFINED_CONSTANTS // EXAMPLES // PCRE_PATTERNS // PCRE_FUNCTIONS // // INTRODUCTION - BEGIN // Introduction // // The syntax for patterns used in these functions closely resembles Perl. The expression must be enclosed in the delimiters, a forward slash (/), for example. Delimiters can be any non-alphanumeric, non-whitespace ASCII character except the backslash (\) and the null byte. If the delimiter character has to be used in the expression itself, it needs to be escaped by backslash. Perl-style (), {}, [], and <> matching delimiters may also be used. See Pattern Syntax for detailed explanation. // The ending delimiter may be followed by various modifiers that affect the matching. See Pattern Modifiers. // Note: This extension maintains a global per-thread cache of compiled regular expressions (up to 4096). // Warning: You should be aware of some limitations of PCRE. Read > http://www.pcre.org/pcre.txt for more info. // The PCRE library is a set of functions that implement regular expression pattern matching using the same syntax and semantics as Perl 5, with just a few differences (see below). The current implementation corresponds to Perl 5.005. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/intro.pcre.php // INTRODUCTION - END // // INSTALLING_CONFIGURING - BEGIN // Installing/Configuring // // REQUIREMENTS // INSTALLATION // RUNTIME_CONFIGURATION // RESOURCE_TYPES // // REQUIREMENTS - BEGIN // Requirements // // No external libraries are needed to build this extension. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/pcre.requirements.php // REQUIREMENTS - END // // INSTALLATION - BEGIN // Installation // // The PCRE extension is a core PHP extension, so it is always enabled. By default, this extension is compiled using the bundled PCRE library. Alternatively, an external PCRE library can be used by passing in the --with-pcre-regex=DIR configuration option where DIR is the location of PCRE's include and library files. It is recommended to use PCRE 8.10 or newer; as of PHP 7.3.0, PCRE2 is required. // PCRE's just-in-time compilation is supported by default, which can be disabled with the --without-pcre-jit configuration option as of PHP 7.0.12. // The Windows version of PHP has built-in support for this extension. You do not need to load any additional extensions in order to use these functions. // PCRE is an active project and as it changes so does the PHP functionality that relies upon it. It is possible that certain parts of the PHP documentation is outdated, in that it may not cover the newest features that PCRE provides. For a list of changes, see the > PCRE library changelog and also the following bundled PCRE history: // // Upgrade history of the bundled PCRE library // PHP Version | Updated PCRE Version | Notes // 8.2.0 | 10.40 | // 8.1.0 | 10.39 | // 7.4.12, 8.0.0 | 10.35 | // 7.4.6 | 10.34 | // 7.4.0 | 10.33 | // 7.3.0 | 10.32 | // 7.2.0 | 8.41 | // 7.0.3 | 8.38 | See CVE-2015-8383, CVE-2015-8386, CVE-2015-8387, CVE-2015-8389, CVE-2015-8390, CVE-2015-8391, CVE-2015-8393, CVE-2015-8394 // 7.0.0 | 8.37 | See CVE-2015-2325, CVE-2015-2326 // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/pcre.installation.php // INSTALLATION - END // // RUNTIME_CONFIGURATION - BEGIN // Runtime Configuration // // The behaviour of these functions is affected by settings in php.ini. // // PCRE Configuration Options // Name | Default | Changeable | Changelog // pcre.backtrack_limit | "1000000" | PHP_INI_ALL | // pcre.recursion_limit | "100000" | PHP_INI_ALL | // pcre.jit | "1" | PHP_INI_ALL | // // For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set. // Here's a short explanation of the configuration directives. // // pcre.backtrack_limit int - PCRE's backtracking limit. Defaults to 100000 for PHP < 5.3.7. // pcre.recursion_limit int - PCRE's recursion limit. Please note that if you set this value to a high number you may consume all the available process stack and eventually crash PHP (due to reaching the stack size limit imposed by the Operating System). // pcre.jit bool - Whether PCRE's just-in-time compilation is going to be used. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/pcre.configuration.php // RUNTIME_CONFIGURATION - END // // RESOURCE_TYPES - BEGIN // Resource Types // // This extension has no resource types defined. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/pcre.resources.php // RESOURCE_TYPES - END // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/pcre.setup.php // INSTALLING_CONFIGURING - END // // PREDEFINED_CONSTANTS - BEGIN // Predefined Constants // // The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime. // // PREG constants // Constants - Description ; As of // PREG_PATTERN_ORDER (int) - Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on. This flag is only used with preg_match_all(). ; // PREG_SET_ORDER (int) - Orders results so that $matches[0] is an array of first set of matches, $matches[1] is an array of second set of matches, and so on. This flag is only used with preg_match_all(). ; // PREG_OFFSET_CAPTURE (int) - See the description of PREG_SPLIT_OFFSET_CAPTURE. ; // PREG_SPLIT_NO_EMPTY (int) - This flag tells preg_split() to return only non-empty pieces. ; // PREG_SPLIT_DELIM_CAPTURE (int) - This flag tells preg_split() to capture parenthesized expression in the delimiter pattern as well. ; // PREG_SPLIT_OFFSET_CAPTURE (int) - If this flag is set, for every occurring match the appendant string offset will also be returned. Note that this changes the return values in an array where every element is an array consisting of the matched string at offset 0 and its string offset within subject at offset 1. This flag is only used for preg_split(). ; // PREG_UNMATCHED_AS_NULL (int) - This flag tells preg_match() and preg_match_all() to include unmatched subpatterns in $matches as null values. Without this flag, unmatched subpatterns are reported as empty strings, as if they were empty matches. Setting this flag allows to distinguish between these two cases. ; 7.2.0 // PREG_NO_ERROR (int) - Returned by preg_last_error() if there were no errors. ; 5.2.0 // PREG_INTERNAL_ERROR (int) - Returned by preg_last_error() if there was an internal PCRE error. ; 5.2.0 // PREG_BACKTRACK_LIMIT_ERROR (int) - Returned by preg_last_error() if backtrack limit was exhausted. ; 5.2.0 // PREG_RECURSION_LIMIT_ERROR (int) - Returned by preg_last_error() if recursion limit was exhausted. ; 5.2.0 // PREG_BAD_UTF8_ERROR (int) - Returned by preg_last_error() if the last error was caused by malformed UTF-8 data (only when running a regex in UTF-8 mode). ; 5.2.0 // PREG_BAD_UTF8_OFFSET_ERROR (int) - Returned by preg_last_error() if the offset didn't correspond to the begin of a valid UTF-8 code point (only when running a regex in UTF-8 mode). ; 5.3.0 // PREG_JIT_STACKLIMIT_ERROR (int) - Returned by preg_last_error() if the last PCRE function failed due to limited JIT stack space. ; 7.0.0 // PCRE_VERSION (string) - PCRE version and release date (e.g. "7.0 18-Dec-2006"). ; 5.2.4 // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/pcre.constants.php // PREDEFINED_CONSTANTS - END // // EXAMPLES - BEGIN // Examples // // [example] // Example #1 Examples of valid patterns // * /<\/\w+>/ // * |(\d{3})-\d+|Sm // * /^(?i)php[34]/ // * {^\s+(\s+)?$} // [/example] // [example] // Example #2 Examples of invalid patterns // * /href='(.*)' - missing ending delimiter // * /\w+\s*\w+/J - unknown modifier 'J' // * 1-\d3-\d3-\d4| - missing starting delimiter // [/example] // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/pcre.examples.php // EXAMPLES - END // // PCRE_PATTERNS - BEGIN // PCRE Patterns // // PATTERN_SYNTAX // PATTERN_MODIFIERS // PERL_DIFFERENCES // // PATTERN_SYNTAX - BEGIN // // INTRODUCTION // DELIMITERS // META_CHARACTERS // ESCAPE_SEQUENCES // UNICODE_CHARACTER_PROPERTIES // ANCHORS // DOT // CHARACTER_CLASSES // ALTERNATION // INTERNAL_OPTION_SETTING // SUBPATTERNS // REPETITION // BACK_REFERENCES // ASSERTIONS // ONCE_ONLY_SUBPATTERNS // CONDITIONAL_SUBPATTERNS // COMMENTS // RECURSIVE_PATTERNS // PERFORMANCE // // INTRODUCTION - BEGIN // Introduction // // The syntax and semantics of the regular expressions supported by PCRE are described below. Regular expressions are also described in the Perl documentation and in a number of other books, some of which have copious examples. Jeffrey Friedl's "Mastering Regular Expressions", published by O'Reilly (ISBN 1-56592-257-3), covers them in great detail. The description here is intended as reference documentation. // A regular expression is a pattern that is matched against a subject string from left to right. Most characters stand for themselves in a pattern, and match the corresponding characters in the subject. As a trivial example, the pattern The quick brown fox matches a portion of a subject string that is identical to itself. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/regexp.introduction.php // INTRODUCTION - END // // DELIMITERS - BEGIN // Delimiters // // When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character. Leading whitespace before a valid delimiter is silently ignored. // Often used delimiters are forward slashes (/), hash signs (#) and tildes (~). The following are all examples of valid delimited patterns. // [code] // /foo bar/ // #^[^0-9]$# // +php+ // %[a-zA-Z0-9_-]% // [/code] // It is also possible to use bracket style delimiters where the opening and closing brackets are the starting and ending delimiter, respectively. (), {}, [] and <> are all valid bracket style delimiter pairs. // [code] // (this [is] a (pattern)) // {this [is] a (pattern)} // [this [is] a (pattern)] // // [/code] // Bracket style delimiters do not need to be escaped when they are used as meta characters within the pattern, but as with other delimiters they must be escaped when they are used as literal characters. // If the delimiter needs to be matched inside the pattern it must be escaped using a backslash. If the delimiter appears often inside the pattern, it is a good idea to choose another delimiter in order to increase readability. // [code] // /http:\/\// // #http://# // [/code] // The preg_quote() function may be used to escape a string for injection into a pattern and its optional second parameter may be used to specify the delimiter to be escaped. // You may add pattern modifiers after the ending delimiter. The following is an example of case-insensitive matching: // [code] // #[a-z]#i // [/code] // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/regexp.reference.delimiters.php // DELIMITERS - END // // META_CHARACTERS - BEGIN // Meta-characters // // The power of regular expressions comes from the ability to include alternatives and repetitions in the pattern. These are encoded in the pattern by the use of meta-characters, which do not stand for themselves but instead are interpreted in some special way. // There are two different sets of meta-characters: those that are recognized anywhere in the pattern except within square brackets, and those that are recognized in square brackets. Outside square brackets, the meta-characters are as follows: // // Meta-characters outside square brackets // Meta-character - Description // \ - general escape character with several uses // ^ - assert start of subject (or line, in multiline mode) // $ - assert end of subject or before a terminating newline (or end of line, in multiline mode) // . - match any character except newline (by default) // [ - start character class definition // ] - end character class definition // | - start of alternative branch // ( - start subpattern // ) - end subpattern // ? - extends the meaning of (, also 0 or 1 quantifier, also makes greedy quantifiers lazy (see repetition) // * - 0 or more quantifier // + - 1 or more quantifier // { - start min/max quantifier // } - end min/max quantifier // Part of a pattern that is in square brackets is called a character class. In a character class the only meta-characters are: // Meta-characters inside square brackets (character classes) // Meta-character - Description // \ - general escape character // ^ - negate the class, but only if the first character // - - indicates character range // The following sections describe the use of each of the meta-characters. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/regexp.reference.meta.php // META_CHARACTERS - END // // ESCAPE_SEQUENCES - BEGIN // Escape sequences // // The backslash character has several uses. Firstly, if it is followed by a non-alphanumeric character, it takes away any special meaning that character may have. This use of backslash as an escape character applies both inside and outside character classes. // For example, if you want to match a "*" character, you write "\*" in the pattern. This applies whether or not the following character would otherwise be interpreted as a meta-character, so it is always safe to precede a non-alphanumeric with "\" to specify that it stands for itself. In particular, if you want to match a backslash, you write "\\". // Note: Single and double quoted PHP strings have special meaning of backslash. Thus if \ has to be matched with a regular expression \\, then "\\\\" or '\\\\' must be used in PHP code. // If a pattern is compiled with the PCRE_EXTENDED option, whitespace in the pattern (other than in a character class) and characters between a "#" outside a character class and the next newline character are ignored. An escaping backslash can be used to include a whitespace or "#" character as part of the pattern. // A second use of backslash provides a way of encoding non-printing characters in patterns in a visible manner. There is no restriction on the appearance of non-printing characters, apart from the binary zero that terminates a pattern, but when a pattern is being prepared by text editing, it is usually easier to use one of the following escape sequences than the binary character it represents: // \a - alarm, that is, the BEL character (hex 07) // \cx - "control-x", where x is any character // \e - escape (hex 1B) // \f - formfeed (hex 0C) // \n - newline (hex 0A) // \p{xx} - a character with the xx property, see unicode properties for more info // \P{xx} - a character without the xx property, see unicode properties for more info // \r - carriage return (hex 0D) // \R - line break: matches \n, \r and \r\n // \t - tab (hex 09) // \xhh - character with hex code hh // \ddd - character with octal code ddd, or backreference // The precise effect of "\cx" is as follows: if "x" is a lower case letter, it is converted to upper case. Then bit 6 of the character (hex 40) is inverted. Thus "\cz" becomes hex 1A, but "\c{" becomes hex 3B, while "\c;" becomes hex 7B. // After "\x", up to two hexadecimal digits are read (letters can be in upper or lower case). In UTF-8 mode, "\x{...}" is allowed, where the contents of the braces is a string of hexadecimal digits. It is interpreted as a UTF-8 character whose code number is the given hexadecimal number. The original hexadecimal escape sequence, \xhh, matches a two-byte UTF-8 character if the value is greater than 127. // After "\0" up to two further octal digits are read. In both cases, if there are fewer than two digits, just those that are present are used. Thus the sequence "\0\x\07" specifies two binary zeros followed by a BEL character. Make sure you supply two digits after the initial zero if the character that follows is itself an octal digit. // The handling of a backslash followed by a digit other than 0 is complicated. Outside a character class, PCRE reads it and any following digits as a decimal number. If the number is less than 10, or if there have been at least that many previous capturing left parentheses in the expression, the entire sequence is taken as a back reference. A description of how this works is given later, following the discussion of parenthesized subpatterns. // Inside a character class, or if the decimal number is greater than 9 and there have not been that many capturing subpatterns, PCRE re-reads up to three octal digits following the backslash, and generates a single byte from the least significant 8 bits of the value. Any subsequent digits stand for themselves. For example: // \040 - is another way of writing a space // \40 - is the same, provided there are fewer than 40 previous capturing subpatterns // \7 - is always a back reference // \11 - might be a back reference, or another way of writing a tab // \011 - is always a tab // \0113 - is a tab followed by the character "3" // \113 - is the character with octal code 113 (since there can be no more than 99 back references) // \377 - is a byte consisting entirely of 1 bits // \81 - is either a back reference, or a binary zero followed by the two characters "8" and "1" // Note that octal values of 100 or greater must not be introduced by a leading zero, because no more than three octal digits are ever read. // All the sequences that define a single byte value can be used both inside and outside character classes. In addition, inside a character class, the sequence "\b" is interpreted as the backspace character (hex 08). Outside a character class it has a different meaning (see below). // The third use of backslash is for specifying generic character types: // \d - any decimal digit // \D - any character that is not a decimal digit // \h - any horizontal whitespace character // \H - any character that is not a horizontal whitespace character // \s - any whitespace character // \S - any character that is not a whitespace character // \v - any vertical whitespace character // \V - any character that is not a vertical whitespace character // \w - any "word" character // \W - any "non-word" character // Each pair of escape sequences partitions the complete set of characters into two disjoint sets. Any given character matches one, and only one, of each pair. // The "whitespace" characters are HT (9), LF (10), FF (12), CR (13), and space (32). However, if locale-specific matching is happening, characters with code points in the range 128-255 may also be considered as whitespace characters, for instance, NBSP (A0). // A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl "word". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale-specific matching is taking place. For example, in the "fr" (French) locale, some character codes greater than 128 are used for accented letters, and these are matched by \w. // These character type sequences can appear both inside and outside character classes. They each match one character of the appropriate type. If the current matching point is at the end of the subject string, all of them fail, since there is no character to match. // The fourth use of backslash is for certain simple assertions. An assertion specifies a condition that has to be met at a particular point in a match, without consuming any characters from the subject string. The use of subpatterns for more complicated assertions is described below. The backslashed assertions are // \b - word boundary // \B - not a word boundary // \A - start of subject (independent of multiline mode) // \Z - end of subject or newline at end (independent of multiline mode) // \z - end of subject (independent of multiline mode) // \G - first matching position in subject // These assertions may not appear in character classes (but note that "\b" has a different meaning, namely the backspace character, inside a character class). // A word boundary is a position in the subject string where the current character and the previous character do not both match \w or \W (i.e. one matches \w and the other matches \W), or the start or end of the string if the first or last character matches \w, respectively. // The \A, \Z, and \z assertions differ from the traditional circumflex and dollar (described in anchors ) in that they only ever match at the very start and end of the subject string, whatever options are set. They are not affected by the PCRE_MULTILINE or PCRE_DOLLAR_ENDONLY options. The difference between \Z and \z is that \Z matches before a newline that is the last character of the string as well as at the end of the string, whereas \z matches only at the end. // The \G assertion is true only when the current matching position is at the start point of the match, as specified by the offset argument of preg_match(). It differs from \A when the value of offset is non-zero. // \Q and \E can be used to ignore regexp metacharacters in the pattern. For example: \w+\Q.$.\E$ will match one or more word characters, followed by literals .$. and anchored at the end of the string. Note that this does not change the behavior of delimiters; for instance the pattern #\Q#\E#$ is not valid, because the second # marks the end of the pattern, and the \E# is interpreted as invalid modifiers. // \K can be used to reset the match start. For example, the pattern foo\Kbar matches "foobar", but reports that it has matched "bar". The use of \K does not interfere with the setting of captured substrings. For example, when the pattern (foo)\Kbar matches "foobar", the first substring is still set to "foo". // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/regexp.reference.escape.php // ESCAPE_SEQUENCES - END // // UNICODE_CHARACTER_PROPERTIES - BEGIN // Unicode character properties // // Since 5.1.0, three additional escape sequences to match generic character types are available when UTF-8 mode is selected. They are: // \p{xx} - a character with the xx property // \P{xx} - a character without the xx property // \X - an extended Unicode sequence // The property names represented by xx above are limited to the Unicode general category properties. Each character has exactly one such property, specified by a two-letter abbreviation. For compatibility with Perl, negation can be specified by including a circumflex between the opening brace and the property name. For example, \p{^Lu} is the same as \P{Lu}. // If only one letter is specified with \p or \P, it includes all the properties that start with that letter. In this case, in the absence of negation, the curly brackets in the escape sequence are optional; these two examples have the same effect: // \p{L} // \pL // // Supported property codes // Property | Matches | Notes // C | Other | // Cc | Control | // Cf | Format | // Cn | Unassigned | // Co | Private use | // Cs | Surrogate | // L | Letter | Includes the following properties: Ll, Lm, Lo, Lt and Lu. // Ll | Lower case letter | // Lm | Modifier letter | // Lo | Other letter | // Lt | Title case letter | // Lu | Upper case letter | // M | Mark | // Mc | Spacing mark | // Me | Enclosing mark | // Mn | Non-spacing mark | // N | Number | // Nd | Decimal number | // Nl | Letter number | // No | Other number | // P | Punctuation | // Pc | Connector punctuation | // Pd | Dash punctuation | // Pe | Close punctuation | // Pf | Final punctuation | // Pi | Initial punctuation | // Po | Other punctuation | // Ps | Open punctuation | // S | Symbol | // Sc | Currency symbol | // Sk | Modifier symbol | // Sm | Mathematical symbol | // So | Other symbol | // Z | Separator | // Zl | Line separator | // Zp | Paragraph separator | // Zs | Space separator | // Extended properties such as InMusicalSymbols are not supported by PCRE. // Specifying case-insensitive (caseless) matching does not affect these escape sequences. For example, \p{Lu} always matches only upper case letters. // Sets of Unicode characters are defined as belonging to certain scripts. A character from one of these sets can be matched using a script name. For example: // * \p{Greek} // * \P{Han} // Those that are not part of an identified script are lumped together as Common. The current list of scripts is: // // Supported scripts // Arabic | Armenian | Avestan | Balinese | Bamum // Batak | Bengali | Bopomofo | Brahmi | Braille // Buginese | Buhid | Canadian_Aboriginal | Carian | Chakma // Cham | Cherokee | Common | Coptic | Cuneiform // Cypriot | Cyrillic | Deseret | Devanagari | Egyptian_Hieroglyphs // Ethiopic | Georgian | Glagolitic | Gothic | Greek // Gujarati | Gurmukhi | Han | Hangul | Hanunoo // Hebrew | Hiragana | Imperial_Aramaic | Inherited | Inscriptional_Pahlavi // Inscriptional_Parthian | Javanese | Kaithi | Kannada | Katakana // Kayah_Li | Kharoshthi | Khmer | Lao | Latin // Lepcha | Limbu | Linear_B | Lisu | Lycian // Lydian | Malayalam | Mandaic | Meetei_Mayek | Meroitic_Cursive // Meroitic_Hieroglyphs | Miao | Mongolian | Myanmar | New_Tai_Lue // Nko | Ogham | Old_Italic | Old_Persian | Old_South_Arabian // Old_Turkic | Ol_Chiki | Oriya | Osmanya | Phags_Pa // Phoenician | Rejang | Runic | Samaritan | Saurashtra // Sharada | Shavian | Sinhala | Sora_Sompeng | Sundanese // Syloti_Nagri | Syriac | Tagalog | Tagbanwa | Tai_Le // Tai_Tham | Tai_Viet | Takri | Tamil | Telugu // Thaana | Thai | Tibetan | Tifinagh | Ugaritic // Vai | Yi // The \X escape matches a Unicode extended grapheme cluster. An extended grapheme cluster is one or more Unicode characters that combine to form a single glyph. In effect, this can be thought of as the Unicode equivalent of . as it will match one composed character, regardless of how many individual characters are actually used to render it. // In versions of PCRE older than 8.32 (which corresponds to PHP versions before 5.4.14 when using the bundled PCRE library). That is, it matches a character without the "mark" property, followed by zero or more characters with the "mark" property, and treats the sequence as an atomic group (see below). Characters with the "mark" property are typically accents that affect the preceding character. // Matching characters by Unicode property is not fast, because PCRE has to search a structure that contains data for over fifteen thousand characters. That is why the traditional escape sequences such as \d and \w do not use Unicode properties in PCRE. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/regexp.reference.unicode.php // UNICODE_CHARACTER_PROPERTIES - END // // ANCHORS - BEGIN // Anchors // // Outside a character class, in the default matching mode, the circumflex character (^) is an assertion which is true only if the current matching point is at the start of the subject string. Inside a character class, circumflex (^) has an entirely different meaning (see below). // Circumflex (^) need not be the first character of the pattern if a number of alternatives are involved, but it should be the first thing in each alternative in which it appears if the pattern is ever to match that branch. If all possible alternatives start with a circumflex (^), that is, if the pattern is constrained to match only at the start of the subject, it is said to be an "anchored" pattern. (There are also other constructs that can cause a pattern to be anchored.) // A dollar character ($) is an assertion which is true only if the current matching point is at the end of the subject string, or immediately before a newline character that is the last character in the string (by default). Dollar ($) need not be the last character of the pattern if a number of alternatives are involved, but it should be the last item in any branch in which it appears. Dollar has no special meaning in a character class. // The meaning of dollar can be changed so that it matches only at the very end of the string, by setting the PCRE_DOLLAR_ENDONLY option at compile or matching time. This does not affect the \Z assertion. // The meanings of the circumflex and dollar characters are changed if the PCRE_MULTILINE option is set. When this is the case, they match immediately after and immediately before an internal "\n" character, respectively, in addition to matching at the start and end of the subject string. For example, the pattern /^abc$/ matches the subject string "def\nabc" in multiline mode, but not otherwise. Consequently, patterns that are anchored in single line mode because all branches start with "^" are not anchored in multiline mode. The PCRE_DOLLAR_ENDONLY option is ignored if PCRE_MULTILINE is set. // Note that the sequences \A, \Z, and \z can be used to match the start and end of the subject in both modes, and if all branches of a pattern start with \A is it always anchored, whether PCRE_MULTILINE is set or not. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/regexp.reference.anchors.php // ANCHORS - END // // DOT - BEGIN // Dot // // Outside a character class, a dot in the pattern matches any one character in the subject, including a non-printing character, but not (by default) newline. If the PCRE_DOTALL option is set, then dots match newlines as well. The handling of dot is entirely independent of the handling of circumflex and dollar, the only relationship being that they both involve newline characters. Dot has no special meaning in a character class. // \C can be used to match single byte. It makes sense in UTF-8 mode where full stop matches the whole character which can consist of multiple bytes. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/regexp.reference.dot.php // DOT - END // // CHARACTER_CLASSES - BEGIN // Character classes // // An opening square bracket introduces a character class, terminated by a closing square bracket. A closing square bracket on its own is not special. If a closing square bracket is required as a member of the class, it should be the first data character in the class (after an initial circumflex, if present) or escaped with a backslash. // A character class matches a single character in the subject; the character must be in the set of characters defined by the class, unless the first character in the class is a circumflex, in which case the subject character must not be in the set defined by the class. If a circumflex is actually required as a member of the class, ensure it is not the first character, or escape it with a backslash. // For example, the character class [aeiou] matches any lower case vowel, while [^aeiou] matches any character that is not a lower case vowel. Note that a circumflex is just a convenient notation for specifying the characters which are in the class by enumerating those that are not. It is not an assertion: it still consumes a character from the subject string, and fails if the current pointer is at the end of the string. // When case-insensitive (caseless) matching is set, any letters in a class represent both their upper case and lower case versions, so for example, an insensitive [aeiou] matches "A" as well as "a", and an insensitive [^aeiou] does not match "A", whereas a sensitive (caseful) version would. // The newline character is never treated in any special way in character classes, whatever the setting of the PCRE_DOTALL or PCRE_MULTILINE options is. A class such as [^a] will always match a newline. // The minus (hyphen) character can be used to specify a range of characters in a character class. For example, [d-m] matches any letter between d and m, inclusive. If a minus character is required in a class, it must be escaped with a backslash or appear in a position where it cannot be interpreted as indicating a range, typically as the first or last character in the class. // It is not possible to have the literal character "]" as the end character of a range. A pattern such as [W-]46] is interpreted as a class of two characters ("W" and "-") followed by a literal string "46]", so it would match "W46]" or "-46]". However, if the "]" is escaped with a backslash it is interpreted as the end of range, so [W-\]46] is interpreted as a single class containing a range followed by two separate characters. The octal or hexadecimal representation of "]" can also be used to end a range. // Ranges operate in ASCII collating sequence. They can also be used for characters specified numerically, for example [\000-\037]. If a range that includes letters is used when case-insensitive (caseless) matching is set, it matches the letters in either case. For example, [W-c] is equivalent to [][\^_`wxyzabc], matched case-insensitively, and if character tables for the "fr" locale are in use, [\xc8-\xcb] matches accented E characters in both cases. // The character types \d, \D, \s, \S, \w, and \W may also appear in a character class, and add the characters that they match to the class. For example, [\dABCDEF] matches any hexadecimal digit. A circumflex can conveniently be used with the upper case character types to specify a more restricted set of characters than the matching lower case type. For example, the class [^\W_] matches any letter or digit, but not underscore. // All non-alphanumeric characters other than \, -, ^ (at the start) and the terminating ] are non-special in character classes, but it does no harm if they are escaped. The pattern terminator is always special and must be escaped when used within an expression. // // Perl supports the POSIX notation for character classes. This uses names enclosed by [: and :] within the enclosing square brackets. PCRE also supports this notation. For example, [01[:alpha:]%] matches "0", "1", any alphabetic character, or "%". The supported class names are: // Character classes // alnum - letters and digits // alpha - letters // ascii - character codes 0 - 127 // blank - space or tab only // cntrl - control characters // digit - decimal digits (same as \d) // graph - printing characters, excluding space // lower - lower case letters // print - printing characters, including space // punct - printing characters, excluding letters and digits // space - white space (not quite the same as \s) // upper - upper case letters // word - "word" characters (same as \w) // xdigit - hexadecimal digits // // The space characters are HT (9), LF (10), VT (11), FF (12), CR (13), and space (32). Notice that this list includes the VT character (code 11). This makes "space" different to \s, which does not include VT (for Perl compatibility). // The name word is a Perl extension, and blank is a GNU extension from Perl 5.8. Another Perl extension is negation, which is indicated by a ^ character after the colon. For example, [12[:^digit:]] matches "1", "2", or any non-digit. // In UTF-8 mode, characters with values greater than 128 do not match any of the POSIX character classes. As of libpcre 8.10 some character classes are changed to use Unicode character properties, in which case the mentioned restriction does not apply. Refer to the > PCRE(3) manual for details. // Unicode character properties can appear inside a character class. They can not be part of a range. The minus (hyphen) character after a Unicode character class will match literally. Trying to end a range with a Unicode character property will result in a warning. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/regexp.reference.character-classes.php // CHARACTER_CLASSES - END // // ALTERNATION - BEGIN // Alternation // // Vertical bar characters are used to separate alternative patterns. For example, the pattern gilbert|sullivan matches either "gilbert" or "sullivan". Any number of alternatives may appear, and an empty alternative is permitted (matching the empty string). The matching process tries each alternative in turn, from left to right, and the first one that succeeds is used. If the alternatives are within a subpattern (defined below), "succeeds" means matching the rest of the main pattern as well as the alternative in the subpattern. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/regexp.reference.alternation.php // ALTERNATION - END // // INTERNAL_OPTION_SETTING - BEGIN // Internal option setting // // The settings of PCRE_CASELESS, PCRE_MULTILINE, PCRE_DOTALL, PCRE_UNGREEDY, PCRE_EXTRA, PCRE_EXTENDED and PCRE_DUPNAMES can be changed from within the pattern by a sequence of Perl option letters enclosed between "(?" and ")". The option letters are: // Internal option letters // i - for PCRE_CASELESS // m - for PCRE_MULTILINE // s - for PCRE_DOTALL // x - for PCRE_EXTENDED // U - for PCRE_UNGREEDY // X - for PCRE_EXTRA (no longer supported as of PHP 7.3.0) // J - for PCRE_INFO_JCHANGED // For example, (?im) sets case-insensitive (caseless), multiline matching. It is also possible to unset these options by preceding the letter with a hyphen, and a combined setting and unsetting such as (?im-sx), which sets PCRE_CASELESS and PCRE_MULTILINE while unsetting PCRE_DOTALL and PCRE_EXTENDED, is also permitted. If a letter appears both before and after the hyphen, the option is unset. // When an option change occurs at top level (that is, not inside subpattern parentheses), the change applies to the remainder of the pattern that follows. So /ab(?i)c/ matches only "abc" and "abC". // If an option change occurs inside a subpattern, the effect is different. This is a change of behaviour in Perl 5.005. An option change inside a subpattern affects only that part of the subpattern that follows it, so (a(?i)b)c matches abc and aBc and no other strings (assuming PCRE_CASELESS is not used). By this means, options can be made to have different settings in different parts of the pattern. Any changes made in one alternative do carry on into subsequent branches within the same subpattern. For example, (a(?i)b|c) matches "ab", "aB", "c", and "C", even though when matching "C" the first branch is abandoned before the option setting. This is because the effects of option settings happen at compile time. There would be some very weird behaviour otherwise. // The PCRE-specific options PCRE_UNGREEDY and PCRE_EXTRA can be changed in the same way as the Perl-compatible options by using the characters U and X respectively. The (?X) flag setting is special in that it must always occur earlier in the pattern than any of the additional features it turns on, even when it is at top level. It is best put at the start. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/regexp.reference.internal-options.php // INTERNAL_OPTION_SETTING - END // // SUBPATTERNS - BEGIN // Subpatterns // // Subpatterns are delimited by parentheses (round brackets), which can be nested. Marking part of a pattern as a subpattern does two things: // 1. It localizes a set of alternatives. For example, the pattern cat(aract|erpillar|) matches one of the words "cat", "cataract", or "caterpillar". Without the parentheses, it would match "cataract", "erpillar" or the empty string. // 2. It sets up the subpattern as a capturing subpattern (as defined above). When the whole pattern matches, that portion of the subject string that matched the subpattern is passed back to the caller via the ovector argument of pcre_exec(). Opening parentheses are counted from left to right (starting from 1) to obtain the numbers of the capturing subpatterns. // For example, if the string "the red king" is matched against the pattern the ((red|white) (king|queen)) the captured substrings are "red king", "red", and "king", and are numbered 1, 2, and 3. // The fact that plain parentheses fulfill two functions is not always helpful. There are often times when a grouping subpattern is required without a capturing requirement. If an opening parenthesis is followed by "?:", the subpattern does not do any capturing, and is not counted when computing the number of any subsequent capturing subpatterns. For example, if the string "the white queen" is matched against the pattern the ((?:red|white) (king|queen)) the captured substrings are "white queen" and "queen", and are numbered 1 and 2. The maximum number of captured substrings is 65535. It may not be possible to compile such large patterns, however, depending on the configuration options of libpcre. // As a convenient shorthand, if any option settings are required at the start of a non-capturing subpattern, the option letters may appear between the "?" and the ":". Thus the two patterns // [code] // (?i:saturday|sunday) // (?:(?i)saturday|sunday) // [/code] // match exactly the same set of strings. Because alternative branches are tried from left to right, and options are not reset until the end of the subpattern is reached, an option setting in one branch does affect subsequent branches, so the above patterns match "SUNDAY" as well as "Saturday". // It is possible to name a subpattern using the syntax (?Ppattern). This subpattern will then be indexed in the matches array by its normal numeric position and also by name. There are two alternative syntaxes (?pattern) and (?'name'pattern). // Sometimes it is necessary to have multiple matching, but alternating subgroups in a regular expression. Normally, each of these would be given their own backreference number even though only one of them would ever possibly match. To overcome this, the (?| syntax allows having duplicate numbers. Consider the following regex matched against the string Sunday: // [code] // (?:(Sat)ur|(Sun))day // [/code] // Here Sun is stored in backreference 2, while backreference 1 is empty. Matching Saturday yields Sat in backreference 1 while backreference 2 does not exist. Changing the pattern to use the (?| fixes this problem: // [code] // (?|(Sat)ur|(Sun))day // [/code] // Using this pattern, both Sun and Sat would be stored in backreference 1. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/regexp.reference.subpatterns.php // SUBPATTERNS - END // // REPETITION - BEGIN // Repetition // // Repetition is specified by quantifiers, which can follow any of the following items: // * a single character, possibly escaped // * the . metacharacter // * a character class // * a back reference (see next section) // * a parenthesized subpattern (unless it is an assertion - see below) // The general repetition quantifier specifies a minimum and maximum number of permitted matches, by giving the two numbers in curly brackets (braces), separated by a comma. The numbers must be less than 65536, and the first must be less than or equal to the second. For example: z{2,4} matches "zz", "zzz", or "zzzz". A closing brace on its own is not a special character. If the second number is omitted, but the comma is present, there is no upper limit; if the second number and the comma are both omitted, the quantifier specifies an exact number of required matches. Thus [aeiou]{3,} matches at least 3 successive vowels, but may match many more, while \d{8} matches exactly 8 digits. An opening curly bracket that appears in a position where a quantifier is not allowed, or one that does not match the syntax of a quantifier, is taken as a literal character. For example, {,6} is not a quantifier, but a literal string of four characters. // The quantifier {0} is permitted, causing the expression to behave as if the previous item and the quantifier were not present. // For convenience (and historical compatibility) the three most common quantifiers have single-character abbreviations: // Single-character quantifiers // * - equivalent to {0,} // + - equivalent to {1,} // ? - equivalent to {0,1} // It is possible to construct infinite loops by following a subpattern that can match no characters with a quantifier that has no upper limit, for example: (a?)* // Earlier versions of Perl and PCRE used to give an error at compile time for such patterns. However, because there are cases where this can be useful, such patterns are now accepted, but if any repetition of the subpattern does in fact match no characters, the loop is forcibly broken. // By default, the quantifiers are "greedy", that is, they match as much as possible (up to the maximum number of permitted times), without causing the rest of the pattern to fail. The classic example of where this gives problems is in trying to match comments in C programs. These appear between the sequences /* and */ and within the sequence, individual * and / characters may appear. An attempt to match C comments by applying the pattern /\*.*\*/ to the string /* first comment */ not comment /* second comment */ fails, because it matches the entire string due to the greediness of the .* item. // However, if a quantifier is followed by a question mark, then it becomes lazy, and instead matches the minimum number of times possible, so the pattern /\*.*?\*/ does the right thing with the C comments. The meaning of the various quantifiers is not otherwise changed, just the preferred number of matches. Do not confuse this use of question mark with its use as a quantifier in its own right. Because it has two uses, it can sometimes appear doubled, as in \d??\d which matches one digit by preference, but can match two if that is the only way the rest of the pattern matches. // If the PCRE_UNGREEDY option is set (an option which is not available in Perl) then the quantifiers are not greedy by default, but individual ones can be made greedy by following them with a question mark. In other words, it inverts the default behaviour. // Quantifiers followed by + are "possessive". They eat as many characters as possible and don't return to match the rest of the pattern. Thus .*abc matches "aabc" but .*+abc doesn't because .*+ eats the whole string. Possessive quantifiers can be used to speed up processing. // When a parenthesized subpattern is quantified with a minimum repeat count that is greater than 1 or with a limited maximum, more store is required for the compiled pattern, in proportion to the size of the minimum or maximum. // If a pattern starts with .* or .{0,} and the PCRE_DOTALL option (equivalent to Perl's /s) is set, thus allowing the . to match newlines, then the pattern is implicitly anchored, because whatever follows will be tried against every character position in the subject string, so there is no point in retrying the overall match at any position after the first. PCRE treats such a pattern as though it were preceded by \A. In cases where it is known that the subject string contains no newlines, it is worth setting PCRE_DOTALL when the pattern begins with .* in order to obtain this optimization, or alternatively using ^ to indicate anchoring explicitly. // When a capturing subpattern is repeated, the value captured is the substring that matched the final iteration. For example, after (tweedle[dume]{3}\s*)+ has matched "tweedledum tweedledee" the value of the captured substring is "tweedledee". However, if there are nested capturing subpatterns, the corresponding captured values may have been set in previous iterations. For example, after /(a|(b))+/ matches "aba" the value of the second captured substring is "b". // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/regexp.reference.repetition.php // REPETITION - END // // BACK_REFERENCES - BEGIN // Back references // // Outside a character class, a backslash followed by a digit greater than 0 (and possibly further digits) is a back reference to a capturing subpattern earlier (i.e. to its left) in the pattern, provided there have been that many previous capturing left parentheses. // However, if the decimal number following the backslash is less than 10, it is always taken as a back reference, and causes an error only if there are not that many capturing left parentheses in the entire pattern. In other words, the parentheses that are referenced need not be to the left of the reference for numbers less than 10. A "forward back reference" can make sense when a repetition is involved and the subpattern to the right has participated in an earlier iteration. See the section escape sequences for further details of the handling of digits following a backslash. // A back reference matches whatever actually matched the capturing subpattern in the current subject string, rather than anything matching the subpattern itself. So the pattern (sens|respons)e and \1ibility matches "sense and sensibility" and "response and responsibility", but not "sense and responsibility". If case-sensitive (caseful) matching is in force at the time of the back reference, then the case of letters is relevant. For example, ((?i)rah)\s+\1 matches "rah rah" and "RAH RAH", but not "RAH rah", even though the original capturing subpattern is matched case-insensitively (caselessly). // There may be more than one back reference to the same subpattern. If a subpattern has not actually been used in a particular match, then any back references to it always fail. For example, the pattern (a|(bc))\2 always fails if it starts to match "a" rather than "bc". Because there may be up to 99 back references, all digits following the backslash are taken as part of a potential back reference number. If the pattern continues with a digit character, then some delimiter must be used to terminate the back reference. If the PCRE_EXTENDED option is set, this can be whitespace. Otherwise an empty comment can be used. // A back reference that occurs inside the parentheses to which it refers fails when the subpattern is first used, so, for example, (a\1) never matches. However, such references can be useful inside repeated subpatterns. For example, the pattern (a|b\1)+ matches any number of "a"s and also "aba", "ababba" etc. At each iteration of the subpattern, the back reference matches the character string corresponding to the previous iteration. In order for this to work, the pattern must be such that the first iteration does not need to match the back reference. This can be done using alternation, as in the example above, or by a quantifier with a minimum of zero. // The \g escape sequence can be used for absolute and relative referencing of subpatterns. This escape sequence must be followed by an unsigned number or a negative number, optionally enclosed in braces. The sequences \1, \g1 and \g{1} are synonymous with one another. The use of this pattern with an unsigned number can help remove the ambiguity inherent when using digits following a backslash. The sequence helps to distinguish back references from octal characters and also makes it easier to have a back reference followed by a literal number, e.g. \g{2}1. // The use of the \g sequence with a negative number signifies a relative reference. For example, (foo)(bar)\g{-1} would match the sequence "foobarbar" and (foo)(bar)\g{-2} matches "foobarfoo". This can be useful in long patterns as an alternative to keeping track of the number of subpatterns in order to reference a specific previous subpattern. // Back references to the named subpatterns can be achieved by (?P=name), \k, \k'name', \k{name}, \g{name}, \g or \g'name'. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/regexp.reference.back-references.php // BACK_REFERENCES - END // // ASSERTIONS - BEGIN // Assertions // // An assertion is a test on the characters following or preceding the current matching point that does not actually consume any characters. The simple assertions coded as \b, \B, \A, \Z, \z, ^ and $ are described in escape sequences. More complicated assertions are coded as subpatterns. There are two kinds: those that look ahead of the current position in the subject string, and those that look behind it. // An assertion subpattern is matched in the normal way, except that it does not cause the current matching position to be changed. Lookahead assertions start with (?= for positive assertions and (?! for negative assertions. For example, \w+(?=;) matches a word followed by a semicolon, but does not include the semicolon in the match, and foo(?!bar) matches any occurrence of "foo" that is not followed by "bar". Note that the apparently similar pattern (?!foo)bar does not find an occurrence of "bar" that is preceded by something other than "foo"; it finds any occurrence of "bar" whatsoever, because the assertion (?!foo) is always true when the next three characters are "bar". A lookbehind assertion is needed to achieve this effect. // Lookbehind assertions start with (?<= for positive assertions and (?)*[!?] matches an unlimited number of substrings that either consist of non-digits, or digits enclosed in <>, followed by either ! or ?. When it matches, it runs quickly. However, if it is applied to aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa it takes a long time before reporting failure. This is because the string can be divided between the two repeats in a large number of ways, and all have to be tried. (The example used [!?] rather than a single character at the end, because both PCRE and Perl have an optimization that allows for fast failure when a single character is used. They remember the last single character that is required for a match, and fail early if it is not present in the string.) // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/regexp.reference.onlyonce.php // ONCE_ONLY_SUBPATTERNS - END // // CONDITIONAL_SUBPATTERNS - BEGIN // Conditional subpatterns // // It is possible to cause the matching process to obey a subpattern conditionally or to choose between two alternative subpatterns, depending on the result of an assertion, or whether a previous capturing subpattern matched or not. The two possible forms of conditional subpattern are // [code] // (?(condition)yes-pattern) // (?(condition)yes-pattern|no-pattern) // [/code] // If the condition is satisfied, the yes-pattern is used; otherwise the no-pattern (if present) is used. If there are more than two alternatives in the subpattern, a compile-time error occurs. // There are two kinds of condition. If the text between the parentheses consists of a sequence of digits, then the condition is satisfied if the capturing subpattern of that number has previously matched. Consider the following pattern, which contains non-significant white space to make it more readable (assume the PCRE_EXTENDED option) and to divide it into three parts for ease of discussion: // [code] // ( \( )? [^()]+ (?(1) \) ) // [/code] // The first part matches an optional opening parenthesis, and if that character is present, sets it as the first captured substring. The second part matches one or more characters that are not parentheses. The third part is a conditional subpattern that tests whether the first set of parentheses matched or not. If they did, that is, if subject started with an opening parenthesis, the condition is true, and so the yes-pattern is executed and a closing parenthesis is required. Otherwise, since no-pattern is not present, the subpattern matches nothing. In other words, this pattern matches a sequence of non-parentheses, optionally enclosed in parentheses. // If the condition is the string (R), it is satisfied if a recursive call to the pattern or subpattern has been made. At "top level", the condition is false. // If the condition is not a sequence of digits or (R), it must be an assertion. This may be a positive or negative lookahead or lookbehind assertion. Consider this pattern, again containing non-significant white space, and with the two alternatives on the second line: // [code] // (?(?=[^a-z]*[a-z]) // \d{2}-[a-z]{3}-\d{2} | \d{2}-\d{2}-\d{2} ) // [/code] // The condition is a positive lookahead assertion that matches an optional sequence of non-letters followed by a letter. In other words, it tests for the presence of at least one letter in the subject. If a letter is found, the subject is matched against the first alternative; otherwise it is matched against the second. This pattern matches strings in one of the two forms dd-aaa-dd or dd-dd-dd, where aaa are letters and dd are digits. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/regexp.reference.conditional.php // CONDITIONAL_SUBPATTERNS - END // // COMMENTS - BEGIN // Comments // // The sequence (?# marks the start of a comment which continues up to the next closing parenthesis. Nested parentheses are not permitted. The characters that make up a comment play no part in the pattern matching at all. // If the PCRE_EXTENDED option is set, an unescaped # character outside a character class introduces a comment that continues up to the next newline character in the pattern. // [example] // Example #1 Usage of comments in PCRE pattern // [php] // // $subject = 'test'; // // /* (?# can be used to add comments without enabling PCRE_EXTENDED */ // $match = preg_match('/te(?# this is a comment)st/', $subject); // var_dump($match); // // /* Whitespace and # is treated as part of the pattern unless PCRE_EXTENDED is enabled */ // $match = preg_match('/te #~~~~ // st/', $subject); // var_dump($match); // // /* When PCRE_EXTENDED is enabled, all whitespace data characters and anything // that follows an unescaped # on the same line is ignored */ // $match = preg_match('/te #~~~~ // st/x', $subject); // var_dump($match); // [/php] // The above example will output: // [result] // int(1) // int(0) // int(1) // [/result] // [/example] // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/regexp.reference.comments.php // COMMENTS - END // // RECURSIVE_PATTERNS - BEGIN // Recursive patterns // // Consider the problem of matching a string in parentheses, allowing for unlimited nested parentheses. Without the use of recursion, the best that can be done is to use a pattern that matches up to some fixed depth of nesting. It is not possible to handle an arbitrary nesting depth. Perl 5.6 has provided an experimental facility that allows regular expressions to recurse (among other things). // First it matches an opening parenthesis. Then it matches any number of substrings which can either be a sequence of non-parentheses, or a recursive match of the pattern itself (i.e. a correctly parenthesized substring). Finally there is a closing parenthesis. // This particular example pattern contains nested unlimited repeats, and so the use of a once-only subpattern for matching strings of non-parentheses is important when applying the pattern to strings that do not match. For example, when it is applied to (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa() it yields "no match" quickly. However, if a once-only subpattern is not used, the match runs for a very long time indeed because there are so many different ways the + and * repeats can carve up the subject, and all have to be tested before failure can be reported. // If the syntax for a recursive subpattern reference (either by number or by name) is used outside the parentheses to which it refers, it operates like a subroutine in a programming language. An earlier example pointed out that the pattern (sens|respons)e and \1ibility matches "sense and sensibility" and "response and responsibility", but not "sense and responsibility". If instead the pattern (sens|respons)e and (?1)ibility is used, it does match "sense and responsibility" as well as the other two strings. Such references must, however, follow the subpattern to which they refer. // The maximum length of a subject string is the largest positive number that an integer variable can hold. However, PCRE uses recursion to handle subpatterns and indefinite repetition. This means that the available stack space may limit the size of a subject string that can be processed by certain patterns. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/regexp.reference.recursive.php // RECURSIVE_PATTERNS - END // // PERFORMANCE - BEGIN // Performance // // Certain items that may appear in patterns are more efficient than others. It is more efficient to use a character class like [aeiou] than a set of alternatives such as (a|e|i|o|u). In general, the simplest construction that provides the required behaviour is usually the most efficient. Jeffrey Friedl's book contains a lot of discussion about optimizing regular expressions for efficient performance. // When a pattern begins with .* and the PCRE_DOTALL option is set, the pattern is implicitly anchored by PCRE, since it can match only at the start of a subject string. However, if PCRE_DOTALL is not set, PCRE cannot make this optimization, because the . metacharacter does not then match a newline, and if the subject string contains newlines, the pattern may match from the character immediately following one of them instead of from the very start. For example, the pattern (.*) second matches the subject "first\nand second" (where \n stands for a newline character) with the first captured substring being "and". In order to do this, PCRE has to retry the match starting after every newline in the subject. // If you are using such a pattern with subject strings that do not contain newlines, the best performance is obtained by setting PCRE_DOTALL, or starting the pattern with ^.* to indicate explicit anchoring. That saves PCRE from having to scan along the subject looking for a newline to restart at. // Beware of patterns that contain nested indefinite repeats. These can take a long time to run when applied to a string that does not match. Consider the pattern fragment (a+)* // This can match "aaaa" in 33 different ways, and this number increases very rapidly as the string gets longer. (The * repeat can match 0, 1, 2, 3, or 4 times, and for each of those cases other than 0, the + repeats can match different numbers of times.) When the remainder of the pattern is such that the entire match is going to fail, PCRE has in principle to try every possible variation, and this can take an extremely long time. // An optimization catches some of the more simple cases such as (a+)*b where a literal character follows. Before embarking on the standard matching procedure, PCRE checks that there is a "b" later in the subject string, and if there is not, it fails the match immediately. However, when there is no following literal this optimization cannot be used. You can see the difference by comparing the behaviour of (a+)*\d with the pattern above. The former gives a failure almost instantly when applied to a whole line of "a" characters, whereas the latter takes an appreciable time with strings longer than about 20 characters. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/regexp.reference.performance.php // PERFORMANCE - END // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/reference.pcre.pattern.syntax.php // PATTERN_SYNTAX - END // // PATTERN_MODIFIERS - BEGIN // Pattern Modifiers // // The current possible PCRE modifiers are listed below. The names in parentheses refer to internal PCRE names for these modifiers. Spaces and newlines are ignored in modifiers, other characters cause error. // i (PCRE_CASELESS) - If this modifier is set, letters in the pattern match both upper and lower case letters. // m (PCRE_MULTILINE) - By default, PCRE treats the subject string as consisting of a single "line" of characters (even if it actually contains several newlines). The "start of line" metacharacter (^) matches only at the start of the string, while the "end of line" metacharacter ($) matches only at the end of the string, or before a terminating newline (unless D modifier is set). This is the same as Perl. When this modifier is set, the "start of line" and "end of line" constructs match immediately following or immediately before any newline in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl's /m modifier. If there are no "\n" characters in a subject string, or no occurrences of ^ or $ in a pattern, setting this modifier has no effect. // s (PCRE_DOTALL) - If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl's /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier. // x (PCRE_EXTENDED) - If this modifier is set, whitespace data characters in the pattern are totally ignored except when escaped or inside a character class, and characters between an unescaped # outside a character class and the next newline character, inclusive, are also ignored. This is equivalent to Perl's /x modifier, and makes it possible to include commentary inside complicated patterns. Note, however, that this applies only to data characters. Whitespace characters may never appear within special character sequences in a pattern, for example within the sequence (?( which introduces a conditional subpattern. // A (PCRE_ANCHORED) - If this modifier is set, the pattern is forced to be "anchored", that is, it is constrained to match only at the start of the string which is being searched (the "subject string"). This effect can also be achieved by appropriate constructs in the pattern itself, which is the only way to do it in Perl. // D (PCRE_DOLLAR_ENDONLY) - If this modifier is set, a dollar metacharacter in the pattern matches only at the end of the subject string. Without this modifier, a dollar also matches immediately before the final character if it is a newline (but not before any other newlines). This modifier is ignored if m modifier is set. There is no equivalent to this modifier in Perl. // S - When a pattern is going to be used several times, it is worth spending more time analyzing it in order to speed up the time taken for matching. If this modifier is set, then this extra analysis is performed. At present, studying a pattern is useful only for non-anchored patterns that do not have a single fixed starting character. // U (PCRE_UNGREEDY) - This modifier inverts the "greediness" of the quantifiers so that they are not greedy by default, but become greedy if followed by ?. It is not compatible with Perl. It can also be set by a (?U) modifier setting within the pattern or by a question mark behind a quantifier (e.g. .*?). // Note: It is usually not possible to match more than pcre.backtrack_limit characters in ungreedy mode. // X (PCRE_EXTRA) - This modifier turns on additional functionality of PCRE that is incompatible with Perl. Any backslash in a pattern that is followed by a letter that has no special meaning causes an error, thus reserving these combinations for future expansion. By default, as in Perl, a backslash followed by a letter with no special meaning is treated as a literal. There are at present no other features controlled by this modifier. // J (PCRE_INFO_JCHANGED) - The (?J) internal option setting changes the local PCRE_DUPNAMES option. Allow duplicate names for subpatterns. As of PHP 7.2.0 J is supported as modifier as well. // u (PCRE_UTF8) - This modifier turns on additional functionality of PCRE that is incompatible with Perl. Pattern and subject strings are treated as UTF-8. An invalid subject will cause the preg_* function to match nothing; an invalid pattern will trigger an error of level E_WARNING. Five and six octet UTF-8 sequences are regarded as invalid. // n (PCRE_NO_AUTO_CAPTURE) - This modifier makes simple (xyz) groups non-capturing. Only named groups like (?xyz) are capturing. This only affects which groups are capturing, it is still possible to use numbered subpattern references, and the matches array will still contain numbered results. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/reference.pcre.pattern.modifiers.php // PATTERN_MODIFIERS - END // // PERL_DIFFERENCES - BEGIN // Perl Differences // // The differences described here are with respect to Perl 5.005. // 1. By default, a whitespace character is any character that the C library function isspace() recognizes, though it is possible to compile PCRE with alternative character type tables. Normally isspace() matches space, formfeed, newline, carriage return, horizontal tab, and vertical tab. Perl 5 no longer includes vertical tab in its set of whitespace characters. The \v escape that was in the Perl documentation for a long time was never in fact recognized. However, the character itself was treated as whitespace at least up to 5.002. In 5.004 and 5.005 it does not match \s. // 2. PCRE does not allow repeat quantifiers on lookahead assertions. Perl permits them, but they do not mean what you might think. For example, (?!a){3} does not assert that the next three characters are not "a". It just asserts that the next character is not "a" three times. // 3. Capturing subpatterns that occur inside negative lookahead assertions are counted, but their entries in the offsets vector are never set. Perl sets its numerical variables from any such patterns that are matched before the assertion fails to match something (thereby succeeding), but only if the negative lookahead assertion contains just one branch. // 4. Though binary zero characters are supported in the subject string, they are not allowed in a pattern string because it is passed as a normal C string, terminated by zero. The escape sequence "\x00" can be used in the pattern to represent a binary zero. // 5. The following Perl escape sequences are not supported: \l, \u, \L, \U. In fact these are implemented by Perl's general string-handling and are not part of its pattern matching engine. // 6. The Perl \G assertion is not supported as it is not relevant to single pattern matches. // 7. Fairly obviously, PCRE does not support the (?{code}) and (??{code}) construction. However, there is support for recursive patterns. // 8. There are at the time of writing some oddities in Perl 5.005_02 concerned with the settings of captured strings when part of a pattern is repeated. For example, matching "aba" against the pattern /^(a(b)?)+$/ sets $2 to the value "b", but matching "aabbaa" against /^(aa(bb)?)+$/ leaves $2 unset. However, if the pattern is changed to /^(aa(b(b))?)+$/ then $2 (and $3) get set. In Perl 5.004 $2 is set in both cases, and that is also true of PCRE. If in the future Perl changes to a consistent state that is different, PCRE may change to follow. // 9. Another as yet unresolved discrepancy is that in Perl 5.005_02 the pattern /^(a)?(?(1)a|b)+$/ matches the string "a", whereas in PCRE it does not. However, in both Perl and PCRE /^(a)?a/ matched against "a" leaves $1 unset. // 10. PCRE provides some extensions to the Perl regular expression facilities: // 10.1 Although lookbehind assertions must match fixed length strings, each alternative branch of a lookbehind assertion can match a different length of string. Perl 5.005 requires them all to have the same length. // 10.2 If PCRE_DOLLAR_ENDONLY is set and PCRE_MULTILINE is not set, the $ meta-character matches only at the very end of the string. // 10.3 If PCRE_EXTRA is set, a backslash followed by a letter with no special meaning is faulted. // 10.4 If PCRE_UNGREEDY is set, the greediness of the repetition quantifiers is inverted, that is, by default they are not greedy, but if followed by a question mark they are. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/reference.pcre.pattern.differences.php // PERL_DIFFERENCES - END // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/pcre.pattern.php // PCRE_PATTERNS - END // // PCRE_FUNCTIONS - BEGIN // PCRE Functions // // Table of Contents // * preg_filter - Perform a regular expression search and replace // * preg_grep - Return array entries that match the pattern // * preg_last_error_msg - Returns the error message of the last PCRE regex execution // * preg_last_error - Returns the error code of the last PCRE regex execution // * preg_match_all - Perform a global regular expression match // * preg_match - Perform a regular expression match // * preg_quote - Quote regular expression characters // * preg_replace_callback_array - Perform a regular expression search and replace using callbacks // * preg_replace_callback - Perform a regular expression search and replace using a callback // * preg_replace - Perform a regular expression search and replace // * preg_split - Split string by a regular expression // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/ref.pcre.php // PCRE_FUNCTIONS - END // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/book.pcre.php // REGULAR_EXPRESSIONS_PERL_COMPATIBLE - END // ============================= // ============================== BEGIN // PHP_TEXT_PCRE_PREG_FILTER // ============================== OFFLINE // ============================== ABOUT // Perform a regular expression search and replace. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // preg_filter() - PHP_5 >= PHP_5_3_0, PHP_7, PHP_8 // ============================== CODE /* function php_text_pcre_preg_filter($pattern, $replacement, $subject, $limit = -1, & $count) { $return_preg_filter = null; // ========== PREG_FILTER - BEGIN // ===== ABOUT // Perform a regular expression search and replace // ===== DESCRIPTION // preg_filter() is identical to preg_replace() except it only returns the (possibly transformed) subjects where there was a match. For details about how this function works, read the preg_replace() documentation. // ===== SUPPORTED // PHP_5 >= PHP_5_3_0, PHP_7, PHP_8 // ===== SYNTAX // preg_filter( // string|array $pattern, // string|array $replacement, // string|array $subject, // int $limit = -1, // int &$count = null // ): string|array|null // ===== CODE $return_preg_filter = preg_filter( // Parameters are described in the documentation for preg_replace(). $pattern, // string|array $pattern $replacement, // string|array $replacement $subject, // string|array $subject $limit, // int $limit $count // int& $count ); // Return Values // Returns an array if the subject parameter is an array, or a string otherwise. // If no matches are found or an error occurred, an empty array is returned when subject is an array or null otherwise. // // Errors/Exceptions // If the regex pattern passed does not compile to a valid regex, an E_WARNING is emitted. // // [examples] // Examples // [example] // Example #1 Example comparing preg_filter() with preg_replace() // [php] // $subject = array('1', 'a', '2', 'b', '3', 'A', 'B', '4'); // $pattern = array('/\d/', '/[a-z]/', '/[1a]/'); // $replace = array('A:$0', 'B:$0', 'C:$0'); // // echo "preg_filter returns\n"; // print_r(preg_filter($pattern, $replace, $subject)); // // echo "preg_replace returns\n"; // print_r(preg_replace($pattern, $replace, $subject)); // [/php] // The above example will output: // [result] // preg_filter returns // Array // ( // [0] => A:C:1 // [1] => B:C:a // [2] => A:2 // [3] => B:b // [4] => A:3 // [7] => A:4 // ) // preg_replace returns // Array // ( // [0] => A:C:1 // [1] => B:C:a // [2] => A:2 // [3] => B:b // [4] => A:3 // [5] => A // [6] => B // [7] => A:4 // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-15) // URL: https://www.php.net/manual/en/function.preg-filter.php // ========== PREG_FILTER - END // SYNTAX: // string|array|null preg_filter(string|array $pattern, string|array $replacement, string|array $subject, int $limit = -1, int& $count) return $return_preg_filter; // string|array|null } */ // ============================== END // PHP_TEXT_PCRE_PREG_FILTER // ============================== // ============================== BEGIN // PHP_TEXT_PCRE_PREG_GREP // ============================== PUBLIC // ============================== ABOUT // Return array entries that match the pattern. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // preg_grep() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_text_pcre_preg_grep($pattern, $array, $flags = 0) { $return_preg_grep = false; // ========== PREG_GREP - BEGIN // ===== ABOUT // Return array entries that match the pattern // ===== DESCRIPTION // Returns the array consisting of the elements of the array array that match the given pattern. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // preg_grep(string $pattern, array $array, int $flags = 0): array|false // ===== CODE $return_preg_grep = preg_grep( $pattern, // string pattern - The pattern to search for, as a string. $array, // array array - The input array. $flags // int flags - 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] // Examples // [example] // Example #1 preg_grep() example // [php] // // return all array elements // // containing floating point numbers // $fl_array = preg_grep("/^(\d+)?\.\d+$/", $array); // [/php] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-15) // URL: https://www.php.net/manual/en/function.preg-grep.php // ========== PREG_GREP - END // SYNTAX: // array|false preg_grep(string $pattern, array $array, int $flags = 0) return $return_preg_grep; // array|false } // ============================== END // PHP_TEXT_PCRE_PREG_GREP // ============================== // ============================== BEGIN // PHP_TEXT_PCRE_PREG_LAST_ERROR_MSG // ============================== OFFLINE // ============================== ABOUT // Returns the error message of the last PCRE regex execution. // ============================== SUPPORT // PHP_8 // ============================== USING FUNCTIONS (1) // preg_last_error_msg() - PHP_8 // ============================== CODE /* function php_text_pcre_preg_last_error_msg() { $return_preg_last_error_msg = null; // ========== PREG_LAST_ERROR_MSG - BEGIN // ===== ABOUT // Returns the error message of the last PCRE regex execution // ===== DESCRIPTION // Returns the error message of the last PCRE regex execution. // ===== SUPPORTED // PHP_8 // ===== SYNTAX // preg_last_error_msg(): string // ===== CODE $return_preg_last_error_msg = preg_last_error_msg( // This function has no parameters. ); // Return Values // Returns the error message on success, or "No error" if no error has occurred. // // [examples] // Examples // [example] // Example #1 preg_last_error_msg() example // [php] // // preg_match('/(?:\D+|<\d+>)*[!?]/', 'foobar foobar foobar'); // // if (preg_last_error() !== PREG_NO_ERROR) { // echo preg_last_error_msg(); // } // // [/php] // The above example will output: // [result] // Backtrack limit exhausted // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-15) // URL: https://www.php.net/manual/en/function.preg-last-error-msg.php // ========== PREG_LAST_ERROR_MSG - END // SYNTAX: // string preg_last_error_msg() return $return_preg_last_error_msg; // string } */ // ============================== END // PHP_TEXT_PCRE_PREG_LAST_ERROR_MSG // ============================== // ============================== BEGIN // PHP_TEXT_PCRE_PREG_LAST_ERROR // ============================== OFFLINE // ============================== ABOUT // Returns the error code of the last PCRE regex execution. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // preg_last_error() - PHP_5 >= PHP_5_2_0, PHP_7, PHP_8 // ============================== CODE /* function php_text_pcre_preg_last_error() { $return_preg_last_error = 0; // ========== PREG_LAST_ERROR - BEGIN // ===== ABOUT // Returns the error code of the last PCRE regex execution // ===== DESCRIPTION // Returns the error code of the last PCRE regex execution. // [example] // Example #1 preg_last_error() example // [php] // // preg_match('/(?:\D+|<\d+>)*[!?]/', 'foobar foobar foobar'); // // if (preg_last_error() == PREG_BACKTRACK_LIMIT_ERROR) { // echo 'Backtrack limit was exhausted!'; // } // // [/php] // The above example will output: // [result] // Backtrack limit was exhausted! // [/result] // [/example] // ===== SUPPORTED // PHP_5 >= PHP_5_2_0, PHP_7, PHP_8 // ===== SYNTAX // preg_last_error(): int // ===== CODE $return_preg_last_error = preg_last_error( // This function has no parameters. ); // Return Values // Returns one of the following constants (explained on their own page): // * PREG_NO_ERROR // * PREG_INTERNAL_ERROR // * PREG_BACKTRACK_LIMIT_ERROR (see also pcre.backtrack_limit) // * PREG_RECURSION_LIMIT_ERROR (see also pcre.recursion_limit) // * PREG_BAD_UTF8_ERROR // * PREG_BAD_UTF8_OFFSET_ERROR // * PREG_JIT_STACKLIMIT_ERROR // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-15) // URL: https://www.php.net/manual/en/function.preg-last-error.php // ========== PREG_LAST_ERROR - END // SYNTAX: // int preg_last_error() return $return_preg_last_error; // int } */ // ============================== END // PHP_TEXT_PCRE_PREG_LAST_ERROR // ============================== // ============================== BEGIN // PHP_TEXT_PCRE_PREG_MATCH_ALL // ============================== PUBLIC // ============================== ABOUT // Perform a global regular expression match. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // preg_match_all() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_text_pcre_preg_match_all($pattern, $subject, & $matches, $flags, $offset) { $return_preg_match_all = false; // ========== PREG_MATCH_ALL - BEGIN // ===== ABOUT // Perform a global regular expression match // ===== DESCRIPTION // Searches subject for all matches to the regular expression given in pattern and puts them in matches in the order specified by flags. // After the first match is found, the subsequent searches are continued on from end of the last match. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // preg_match_all( // string $pattern, // string $subject, // array &$matches = null, // int $flags = 0, // int $offset = 0 // ): int|false // ===== CODE $return_preg_match_all = preg_match_all( $pattern, // string pattern - The pattern to search for, as a string. $subject, // string subject - The input string. $matches, // array& matches - Array of all matches in multi-dimensional array ordered according to flags. $flags, // int flags - Can be a combination of the following flags (note that it doesn't make sense to use PREG_PATTERN_ORDER together with PREG_SET_ORDER): // // PREG_PATTERN_ORDER - Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on. // [example] // [php] // preg_match_all("|<[^>]+>(.*)]+>|U", // "example:
this is a test
", // $out, PREG_PATTERN_ORDER); // echo $out[0][0] . ", " . $out[0][1] . "\n"; // echo $out[1][0] . ", " . $out[1][1] . "\n"; // [/php] // The above example will output: // [result] // example: ,
this is a test
// example: , this is a test // [/result] // [/example] // So, $out[0] contains array of strings that matched full pattern, and $out[1] contains array of strings enclosed by tags. // If the pattern contains named subpatterns, $matches additionally contains entries for keys with the subpattern name. // If the pattern contains duplicate named subpatterns, only the rightmost subpattern is stored in $matches[NAME]. // [example] // [php] // preg_match_all( // '/(?J)(?foo)|(?bar)/', // 'foo bar', // $matches, // PREG_PATTERN_ORDER // ); // print_r($matches['match']); // [/php] // The above example will output: // [result] // Array // ( // [0] => // [1] => bar // ) // [/result] // [/example] // // PREG_SET_ORDER - Orders results so that $matches[0] is an array of first set of matches, $matches[1] is an array of second set of matches, and so on. // [example] // [php] // preg_match_all("|<[^>]+>(.*)]+>|U", // "example:
this is a test
", // $out, PREG_SET_ORDER); // echo $out[0][0] . ", " . $out[0][1] . "\n"; // echo $out[1][0] . ", " . $out[1][1] . "\n"; // [/php] // The above example will output: // [result] // example: , example: //
this is a test
, this is a test // [/result] // [/example] // // PREG_OFFSET_CAPTURE - If this flag is passed, for every occurring match the appendant string offset (in bytes) will also be returned. Note that this changes the value of matches into an array of arrays where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1. // [example] // [php] // preg_match_all('/(foo)(bar)(baz)/', 'foobarbaz', $matches, PREG_OFFSET_CAPTURE); // print_r($matches); // [/php] // The above example will output: // [result] // Array // ( // [0] => Array // ( // [0] => Array // ( // [0] => foobarbaz // [1] => 0 // ) // ) // [1] => Array // ( // [0] => Array // ( // [0] => foo // [1] => 0 // ) // ) // [2] => Array // ( // [0] => Array // ( // [0] => bar // [1] => 3 // ) // ) // [3] => Array // ( // [0] => Array // ( // [0] => baz // [1] => 6 // ) // ) // ) // [/result] // [/example] // // PREG_UNMATCHED_AS_NULL - If this flag is passed, unmatched subpatterns are reported as null; otherwise they are reported as an empty string. // If no order flag is given, PREG_PATTERN_ORDER is assumed. $offset // int offset - Normally, the search starts from the beginning of the subject string. The optional parameter offset can be used to specify the alternate place from which to start the search (in bytes). // Note: Using offset is not equivalent to passing substr($subject, $offset) to preg_match_all() in place of the subject string, because pattern can contain assertions such as ^, $ or (?<=x). See preg_match() for examples. ); // Return Values // Returns the number of full pattern matches (which might be zero), or false on failure. // // Errors/Exceptions // If the regex pattern passed does not compile to a valid regex, an E_WARNING is emitted. // // Changelog // Version - Description // 7.2.0 - The PREG_UNMATCHED_AS_NULL is now supported for the $flags parameter. // // [examples] // Examples // [example] // Example #1 Getting all phone numbers out of some text. // [php] // preg_match_all("/\(? (\d{3})? \)? (?(1) [\-\s] ) \d{3}-\d{4}/x", // "Call 555-1212 or 1-800-555-1212", $phones); // [/php] // [/example] // [example] // Example #2 Find matching HTML tags (greedy) // [php] // // The \\2 is an example of backreferencing. This tells pcre that // // it must match the second set of parentheses in the regular expression // // itself, which would be the ([\w]+) in this case. The extra backslash is // // required because the string is in double quotes. // $html = "bold textclick me"; // // preg_match_all("/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/", $html, $matches, PREG_SET_ORDER); // // foreach ($matches as $val) { // echo "matched: " . $val[0] . "\n"; // echo "part 1: " . $val[1] . "\n"; // echo "part 2: " . $val[2] . "\n"; // echo "part 3: " . $val[3] . "\n"; // echo "part 4: " . $val[4] . "\n\n"; // } // [/php] // The above example will output: // [result] // matched: bold text // part 1: // part 2: b // part 3: bold text // part 4: // // matched: click me // part 1: // part 2: a // part 3: click me // part 4: // [/result] // [/example] // [example] // Example #3 Using named subpattern // [php] // // $str = <<\w+): (?P\d+)/', $str, $matches); // // /* Alternative */ // // preg_match_all('/(?\w+): (?\d+)/', $str, $matches); // // print_r($matches); // // [/php] // The above example will output: // [result] // Array // ( // [0] => Array // ( // [0] => a: 1 // [1] => b: 2 // [2] => c: 3 // ) // // [name] => Array // ( // [0] => a // [1] => b // [2] => c // ) // // [1] => Array // ( // [0] => a // [1] => b // [2] => c // ) // // [digit] => Array // ( // [0] => 1 // [1] => 2 // [2] => 3 // ) // // [2] => Array // ( // [0] => 1 // [1] => 2 // [2] => 3 // ) // // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2023-09-19) // URL: https://www.php.net/manual/en/function.preg-match-all.php // ========== PREG_MATCH_ALL - END // SYNTAX: // int|false preg_match_all(string $pattern, string $subject, array& $matches, int $flags, int $offset) return $return_preg_match_all; // int|false } // ============================== END // PHP_TEXT_PCRE_PREG_MATCH_ALL // ============================== // ============================== BEGIN // PHP_TEXT_PCRE_PREG_MATCH // ============================== PUBLIC // ============================== ABOUT // Perform a regular expression match. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // preg_match() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_text_pcre_preg_match($pattern, $subject, & $matches, $flags, $offset) { $return_preg_match = false; // ========== PREG_MATCH - BEGIN // ===== ABOUT // Perform a regular expression match // ===== DESCRIPTION // Searches subject for a match to the regular expression given in pattern. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // preg_match( // string $pattern, // string $subject, // array &$matches = null, // int $flags = 0, // int $offset = 0 // ): int|false // ===== CODE $return_preg_match = preg_match( $pattern, // string pattern - The pattern to search for, as a string. $subject, // string subject - The input string. $matches, // array& matches - If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on. $flags, // int flags - flags can be a combination of the following flags: // // PREG_OFFSET_CAPTURE - If this flag is passed, for every occurring match the appendant string offset (in bytes) will also be returned. Note that this changes the value of matches into an array where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1. // [example] // [php] // preg_match('/(foo)(bar)(baz)/', 'foobarbaz', $matches, PREG_OFFSET_CAPTURE); // print_r($matches); // [/php] // The above example will output: // [result] // Array // ( // [0] => Array // ( // [0] => foobarbaz // [1] => 0 // ) // [1] => Array // ( // [0] => foo // [1] => 0 // ) // [2] => Array // ( // [0] => bar // [1] => 3 // ) // [3] => Array // ( // [0] => baz // [1] => 6 // ) // ) // [/result] // [/example] // // PREG_UNMATCHED_AS_NULL - If this flag is passed, unmatched subpatterns are reported as null; otherwise they are reported as an empty string. // [example] // [php] // preg_match('/(a)(b)*(c)/', 'ac', $matches); // var_dump($matches); // preg_match('/(a)(b)*(c)/', 'ac', $matches, PREG_UNMATCHED_AS_NULL); // var_dump($matches); // [/php] // The above example will output: // [result] // array(4) { // [0]=> // string(2) "ac" // [1]=> // string(1) "a" // [2]=> // string(0) "" // [3]=> // string(1) "c" // } // array(4) { // [0]=> // string(2) "ac" // [1]=> // string(1) "a" // [2]=> // NULL // [3]=> // string(1) "c" // } // [/result] // [/example] $offset // int offset - Normally, the search starts from the beginning of the subject string. The optional parameter offset can be used to specify the alternate place from which to start the search (in bytes). // Note: // Using offset is not equivalent to passing substr($subject, $offset) to preg_match() in place of the subject string, because pattern can contain assertions such as ^, $ or (?<=x). Compare: // [example] // [php] // $subject = "abcdef"; // $pattern = '/^def/'; // preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3); // print_r($matches); // [/php] // The above example will output: /// [result] // Array // ( // ) // [/result] // while this example // [php] // $subject = "abcdef"; // $pattern = '/^def/'; // preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CAPTURE); // print_r($matches); // [/php] // will produce /// [result] // Array // ( // [0] => Array // ( // [0] => def // [1] => 0 // ) // ) /// [/result] // [/example] // Alternatively, to avoid using substr(), use the \G assertion rather than the ^ anchor, or the A modifier instead, both of which work with the offset parameter. ); // Return Values // preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or false on failure. // Warning: This function may return Boolean false, but may also return a non-Boolean value which evaluates to false. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. // // Errors/Exceptions // If the regex pattern passed does not compile to a valid regex, an E_WARNING is emitted. // // Changelog // Version - Description // 7.2.0 - The PREG_UNMATCHED_AS_NULL is now supported for the $flags parameter. // // [examples] // Examples // [example] // Example #1 Find the string of text "php" // [php] // // The "i" after the pattern delimiter indicates a case-insensitive search // if (preg_match("/php/i", "PHP is the web scripting language of choice.")) { // echo "A match was found."; // } else { // echo "A match was not found."; // } // [/php] // [/example] // [example] // Example #2 Find the word "web" // [php] // /* The \b in the pattern indicates a word boundary, so only the distinct // * word "web" is matched, and not a word partial like "webbing" or "cobweb" */ // if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) { // echo "A match was found."; // } else { // echo "A match was not found."; // } // // if (preg_match("/\bweb\b/i", "PHP is the website scripting language of choice.")) { // echo "A match was found."; // } else { // echo "A match was not found."; // } // [/php] // [/example] // [example] // Example #3 Getting the domain name out of a URL // [php] // // get host name from URL // preg_match('@^(?:http://)?([^/]+)@i', // "http://www.php.net/index.html", $matches); // $host = $matches[1]; // // // get last two segments of host name // preg_match('/[^.]+\.[^.]+$/', $host, $matches); // echo "domain name is: {$matches[0]}\n"; // [/php] // The above example will output: // [result] // domain name is: php.net // [/result] // [/example] // [example] // Example #4 Using named subpattern // [php] // // $str = 'foobar: 2008'; // // preg_match('/(?P\w+): (?P\d+)/', $str, $matches); // // /* Alternative */ // // preg_match('/(?\w+): (?\d+)/', $str, $matches); // // print_r($matches); // // [/php] // The above example will output: // [result] // Array // ( // [0] => foobar: 2008 // [name] => foobar // [1] => foobar // [digit] => 2008 // [2] => 2008 // ) // [/result] // [/example] // [/examples] // // Notes // Tip: Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() instead as it will be faster. // ===== LITERATURE_SOURCES // * PHP_NET (2023-09-19) // URL: https://www.php.net/manual/en/function.preg-match.php // ========== PREG_MATCH - END // SYNTAX: // int|false preg_match(string $pattern, string $subject, array& $matches, int $flags, int $offset) return $return_preg_match; // int|false } // ============================== END // PHP_TEXT_PCRE_PREG_MATCH // ============================== // ============================== BEGIN // PHP_TEXT_PCRE_PREG_QUOTE // ============================== PUBLIC // ============================== ABOUT // Quote regular expression characters. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // preg_quote() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_text_pcre_preg_quote($str, $delimiter = null) { $return_preg_quote = null; // ========== PREG_QUOTE - BEGIN // ===== ABOUT // Quote regular expression characters // ===== DESCRIPTION // preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters. // The special regular expression characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : - # // Note that / is not a special regular expression character. // Note: Note that preg_quote() is not meant to be applied to the $replacement string(s) of preg_replace() etc. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // preg_quote(string $str, ?string $delimiter = null): string // ===== CODE $return_preg_quote = preg_quote( $str, // string str - The input string. $delimiter // string delimiter - If the optional delimiter is specified, it will also be escaped. This is useful for escaping the delimiter that is required by the PCRE functions. The / is the most commonly used delimiter. ); // Return Values // Returns the quoted (escaped) string. // // Changelog // Version - Description // 7.3.0 - The # character is now quoted // 7.2.0 - delimiter is nullable now. // // [examples] // Examples // [example] // Example #1 preg_quote() example // [php] // $keywords = '$40 for a g3/400'; // $keywords = preg_quote($keywords, '/'); // echo $keywords; // returns \$40 for a g3\/400 // [/php] // [/example] // [example] // Example #2 Italicizing a word within some text // [php] // // In this example, preg_quote($word) is used to keep the // // asterisks from having special meaning to the regular // // expression. // // $textbody = "This book is *very* difficult to find."; // $word = "*very*"; // $textbody = preg_replace ("/" . preg_quote($word, '/') . "/", // "" . $word . "", // $textbody); // [/php] // [/example] // [/examples] // // Notes // Note: This function is binary-safe. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-15) // URL: https://www.php.net/manual/en/function.preg-quote.php // ========== PREG_QUOTE - END // SYNTAX: // string preg_quote(string $str, string $delimiter = null) return $return_preg_quote; // string } // ============================== END // PHP_TEXT_PCRE_PREG_QUOTE // ============================== // ============================== BEGIN // PHP_TEXT_PCRE_PREG_REPLACE_CALLBACK_ARRAY // ============================== OFFLINE // ============================== ABOUT // Perform a regular expression search and replace using callbacks. // ============================== SUPPORT // PHP_7 - PHP_8 // ============================== USING FUNCTIONS (1) // preg_replace_callback_array() - PHP_7, PHP_8 // ============================== CODE /* function php_text_pcre_preg_replace_callback_array($pattern, $subject, $limit = -1, & $count, $flags) { $return_preg_replace_callback_array = null; // ========== PREG_REPLACE_CALLBACK_ARRAY - BEGIN // ===== ABOUT // Perform a regular expression search and replace using callbacks // ===== DESCRIPTION // The behavior of this function is similar to preg_replace_callback(), except that callbacks are executed on a per-pattern basis. // ===== SUPPORTED // PHP_7, PHP_8 // ===== SYNTAX // preg_replace_callback_array( // array $pattern, // string|array $subject, // int $limit = -1, // int &$count = null, // int $flags = 0 // ): string|array|null // ===== CODE $return_preg_replace_callback_array = preg_replace_callback_array( $pattern, // array pattern - An associative array mapping patterns (keys) to callables (values). $subject, // string|array subject - The string or an array with strings to search and replace. $limit, // int limit - The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit). $count, // int& count - If specified, this variable will be filled with the number of replacements done. $flags // int flags - flags can be a combination of the PREG_OFFSET_CAPTURE and PREG_UNMATCHED_AS_NULL flags, which influence the format of the matches array. See the description in preg_match() for more details. ); // Return Values // preg_replace_callback_array() returns an array if the subject parameter is an array, or a string otherwise. On errors the return value is null // If matches are found, the new subject will be returned, otherwise subject will be returned unchanged. // // Errors/Exceptions // If the regex pattern passed does not compile to a valid regex, an E_WARNING is emitted. // // Changelog // Version - Description // 7.4.0 - The flags parameter was added. // // [examples] // Examples // [example] // Example #1 preg_replace_callback_array() example // [php] // $subject = 'Aaaaaa Bbb'; // // preg_replace_callback_array( // [ // '~[a]+~i' => function ($match) { // echo strlen($match[0]), ' matches for "a" found', PHP_EOL; // }, // '~[b]+~i' => function ($match) { // echo strlen($match[0]), ' matches for "b" found', PHP_EOL; // } // ], // $subject // ); // [/php] // The above example will output: // [result] // 6 matches for "a" found // 3 matches for "b" found // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-15) // URL: https://www.php.net/manual/en/function.preg-replace-callback-array.php // ========== PREG_REPLACE_CALLBACK_ARRAY - END // SYNTAX: // string|array|null preg_replace_callback_array(array $pattern, string|array $subject, int $limit = -1, int& $count, int $flags) return $return_preg_replace_callback_array; // string|array|null } */ // ============================== END // PHP_TEXT_PCRE_PREG_REPLACE_CALLBACK_ARRAY // ============================== // ============================== BEGIN // PHP_TEXT_PCRE_PREG_REPLACE_CALLBACK // ============================== PUBLIC // ============================== ABOUT // Perform a regular expression search and replace using a callback. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // preg_replace_callback() - PHP_4 >= PHP_4_0_5, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_text_pcre_preg_replace_callback($pattern, $callback, $subject, $limit = -1, & $count, $flags) { $return_preg_replace_callback = null; // ========== PREG_REPLACE_CALLBACK - BEGIN // ===== ABOUT // Perform a regular expression search and replace using a callback // ===== DESCRIPTION // The behavior of this function is almost identical to preg_replace(), except for the fact that instead of replacement parameter, one should specify a callback. // ===== SUPPORTED // PHP_4 >= PHP_4_0_5, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // preg_replace_callback( // string|array $pattern, // callable $callback, // string|array $subject, // int $limit = -1, // int &$count = null, // int $flags = 0 // ): string|array|null // ===== CODE $return_preg_replace_callback = preg_replace_callback( $pattern, // string|array pattern - The pattern to search for. It can be either a string or an array with strings. $callback, // callable callback - A callback that will be called and passed an array of matched elements in the subject string. The callback should return the replacement string. This is the callback signature: // handler(array $matches): string // You'll often need the callback function for a preg_replace_callback() in just one place. In this case you can use an anonymous function to declare the callback within the call to preg_replace_callback(). By doing it this way you have all information for the call in one place and do not clutter the function namespace with a callback function's name not used anywhere else. // [example] // Example #1 preg_replace_callback() and anonymous function // [php] // // a unix-style command line filter to convert uppercase // // letters at the beginning of paragraphs to lowercase // $fp = fopen("php://stdin", "r") or die("can't read stdin"); // while (!feof($fp)) { // $line = fgets($fp); // $line = preg_replace_callback( // '|

\s*\w|', // function ($matches) { // return strtolower($matches[0]); // }, // $line // ); // echo $line; // } // fclose($fp); // [/php] // [/example] $subject, // string|array subject - The string or an array with strings to search and replace. $limit, // int limit - The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit). $count, // int& count - If specified, this variable will be filled with the number of replacements done. $flags // int flags - flags can be a combination of the PREG_OFFSET_CAPTURE and PREG_UNMATCHED_AS_NULL flags, which influence the format of the matches array. See the description in preg_match() for more details. ); // Return Values // preg_replace_callback() returns an array if the subject parameter is an array, or a string otherwise. On errors the return value is null // If matches are found, the new subject will be returned, otherwise subject will be returned unchanged. // // Errors/Exceptions // If the regex pattern passed does not compile to a valid regex, an E_WARNING is emitted. // // Changelog // Version - Description // 7.4.0 - The flags parameter was added. // // [examples] // Examples // [example] // Example #2 preg_replace_callback() example // [php] // // this text was used in 2002 // // we want to get this up to date for 2003 // $text = "April fools day is 04/01/2002\n"; // $text.= "Last christmas was 12/24/2001\n"; // // the callback function // function next_year($matches) // { // // as usual: $matches[0] is the complete match // // $matches[1] the match for the first subpattern // // enclosed in '(...)' and so on // return $matches[1].($matches[2]+1); // } // echo preg_replace_callback( // "|(\d{2}/\d{2}/)(\d{4})|", // "next_year", // $text); // // [/php] // The above example will output: // [result] // April fools day is 04/01/2003 // Last christmas was 12/24/2002 // [/result] // [/example] // [example] // Example #3 preg_replace_callback() using recursive structure to handle encapsulated BB code // [php] // $input = "plain [indent] deep [indent] deeper [/indent] deep [/indent] plain"; // // function parseTagsRecursive($input) // { // // $regex = '#\[indent]((?:[^[]|\[(?!/?indent])|(?R))+)\[/indent]#'; // // if (is_array($input)) { // $input = '

'.$input[1].'
'; // } // // return preg_replace_callback($regex, 'parseTagsRecursive', $input); // } // // $output = parseTagsRecursive($input); // // echo $output; // [/php] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2023-09-19) // URL: https://www.php.net/manual/en/function.preg-replace-callback.php // ========== PREG_REPLACE_CALLBACK - END // SYNTAX: // string|array|null preg_replace_callback(string|array $pattern, callable $callback, string|array $subject, int $limit = -1, int& $count, int $flags) return $return_preg_replace_callback; // string|array|null } // ============================== END // PHP_TEXT_PCRE_PREG_REPLACE_CALLBACK // ============================== // ============================== BEGIN // PHP_TEXT_PCRE_PREG_REPLACE // ============================== PUBLIC // ============================== ABOUT // Perform a regular expression search and replace. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // preg_replace() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_text_pcre_preg_replace($pattern, $replacement, $subject, $limit = -1, & $count) { $return_preg_replace = null; // ========== PREG_REPLACE - BEGIN // ===== ABOUT // Perform a regular expression search and replace // ===== DESCRIPTION // Searches subject for matches to pattern and replaces them with replacement. // To match an exact string, rather than a pattern, consider using str_replace() or str_ireplace() instead of this function. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // preg_replace( // string|array $pattern, // string|array $replacement, // string|array $subject, // int $limit = -1, // int &$count = null // ): string|array|null // ===== CODE $return_preg_replace = preg_replace( $pattern, // string|array pattern - The pattern to search for. It can be either a string or an array with strings. // Several PCRE modifiers are also available. $replacement, // string|array replacement - The string or an array with strings to replace. If this parameter is a string and the pattern parameter is an array, all patterns will be replaced by that string. If both pattern and replacement parameters are arrays, each pattern will be replaced by the replacement counterpart. If there are fewer elements in the replacement array than in the pattern array, any extra patterns will be replaced by an empty string. // replacement may contain references of the form \n or $n, with the latter form being the preferred one. Every such reference will be replaced by the text captured by the n'th parenthesized pattern. n can be from 0 to 99, and \0 or $0 refers to the text matched by the whole pattern. Opening parentheses are counted from left to right (starting from 1) to obtain the number of the capturing subpattern. Note that backslashes in string literals may require to be escaped. // When working with a replacement pattern where a backreference is immediately followed by another number (i.e.: placing a literal number immediately after a matched pattern), you cannot use the familiar \1 notation for your backreference. \11, for example, would confuse preg_replace() since it does not know whether you want the \1 backreference followed by a literal 1, or the \11 backreference followed by nothing. In this case the solution is to use ${1}1. This creates an isolated $1 backreference, leaving the 1 as a literal. // When using the deprecated e modifier, this function escapes some characters (namely ', ", \ and NULL) in the strings that replace the backreferences. This is done to ensure that no syntax errors arise from backreference usage with either single or double quotes (e.g. 'strlen(\'$1\')+strlen("$2")'). Make sure you are aware of PHP's string syntax to know exactly how the interpreted string will look. $subject, // string|array subject - The string or an array with strings to search and replace. // If subject is an array, then the search and replace is performed on every entry of subject, and the return value is an array as well. // If the subject array is associative, keys will be preserved in the returned value. $limit, // int limit - The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit). $count // int& count - If specified, this variable will be filled with the number of replacements done. ); // Return Values // preg_replace() returns an array if the subject parameter is an array, or a string otherwise. // If matches are found, the new subject will be returned, otherwise subject will be returned unchanged or null if an error occurred. // // Errors/Exceptions // Using the "\e" modifier is an error; an E_WARNING is emitted in this case. // If the regex pattern passed does not compile to a valid regex, an E_WARNING is emitted. // // [examples] // Examples // [example] // Example #1 Using backreferences followed by numeric literals // [php] // $string = 'April 15, 2003'; // $pattern = '/(\w+) (\d+), (\d+)/i'; // $replacement = '${1}1,$3'; // echo preg_replace($pattern, $replacement, $string); // [/php] // The above example will output: // [result] // April1,2003 // [/result] // [/example] // [example] // Example #2 Using indexed arrays with preg_replace() // [php] // $string = 'The quick brown fox jumps over the lazy dog.'; // $patterns = array(); // $patterns[0] = '/quick/'; // $patterns[1] = '/brown/'; // $patterns[2] = '/fox/'; // $replacements = array(); // $replacements[2] = 'bear'; // $replacements[1] = 'black'; // $replacements[0] = 'slow'; // echo preg_replace($patterns, $replacements, $string); // [/php] // The above example will output: // [result] // The bear black slow jumps over the lazy dog. // [/result] // By ksorting patterns and replacements, we should get what we wanted. // [php] // ksort($patterns); // ksort($replacements); // echo preg_replace($patterns, $replacements, $string); // [/php] // The above example will output: // [result] // The slow black bear jumps over the lazy dog. // [/result] // [/example] // [example] // Example #3 Replacing several values // [php] // $patterns = array ('/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/', // '/^\s*{(\w+)}\s*=/'); // $replace = array ('\3/\4/\1\2', '$\1 ='); // echo preg_replace($patterns, $replace, '{startDate} = 1999-5-27'); // [/php] // The above example will output: // [result] // $startDate = 5/27/1999 // [/result] // [/example] // [example] // Example #4 Strip whitespace // This example strips excess whitespace from a string. // [php] // $str = 'foo o'; // $str = preg_replace('/\s\s+/', ' ', $str); // // This will be 'foo o' now // echo $str; // [/php] // [/example] // [example] // Example #5 Using the count parameter // [php] // $count = 0; // // echo preg_replace(array('/\d/', '/\s/'), '*', 'xp 4 to', -1 , $count); // echo $count; //3 // [/php] // The above example will output: // [result] // xp***to // 3 // [/result] // [/example] // [/examples] // // Notes // Note: When using arrays with pattern and replacement, the keys are processed in the order they appear in the array. This is not necessarily the same as the numerical index order. If you use indexes to identify which pattern should be replaced by which replacement, you should perform a ksort() on each array prior to calling preg_replace(). // Note: // When both pattern and replacement are arrays, matching rules will operate sequentially. That is, the second pattern/replacement pair will operate on the string that results from the first pattern/replacement pair, not the original string. If you want to simulate replacements operating in parallel, such as swapping two values, replace one pattern by an intermediary placeholder, then in a later pair replace that intermediary placeholder with the desired replacement. // [php] // $p = array('/a/', '/b/', '/c/'); // $r = array('b', 'c', 'd'); // print_r(preg_replace($p, $r, 'a')); // // prints d // [/php] // ===== LITERATURE_SOURCES // * PHP_NET (2023-09-19) // URL: https://www.php.net/manual/en/function.preg-replace.php // ========== PREG_REPLACE - END // SYNTAX: // string|array|null preg_replace(string|array $pattern, string|array $replacement, string|array $subject, int $limit = -1, int& $count) return $return_preg_replace; // string|array|null } // ============================== END // PHP_TEXT_PCRE_PREG_REPLACE // ============================== // ============================== BEGIN // PHP_TEXT_PCRE_PREG_SPLIT // ============================== PUBLIC // ============================== ABOUT // Split string by a regular expression. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // preg_split() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_text_pcre_preg_split($pattern, $subject, $limit = -1, $flags = 0) { $return_preg_split = false; // ========== PREG_SPLIT - BEGIN // ===== ABOUT // Split string by a regular expression // ===== DESCRIPTION // Split the given string by a regular expression. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // preg_split( // string $pattern, // string $subject, // int $limit = -1, // int $flags = 0 // ): array|false // ===== CODE $return_preg_split = preg_split( $pattern, // string pattern - The pattern to search for, as a string. $subject, // string subject - The input string. $limit, // int limit - If specified, then only substrings up to limit are returned with the rest of the string being placed in the last substring. A limit of -1 or 0 means "no limit". $flags // int flags - flags can be any combination of the following flags (combined with the | bitwise operator): // PREG_SPLIT_NO_EMPTY - If this flag is set, only non-empty pieces will be returned by preg_split(). // PREG_SPLIT_DELIM_CAPTURE - If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well. // PREG_SPLIT_OFFSET_CAPTURE - If this flag is set, for every occurring match the appendant string offset will also be returned. Note that this changes the return value in an array where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1. ); // Return Values // Returns an array containing substrings of subject split along boundaries matched by pattern, or false on failure. // // Errors/Exceptions // If the regex pattern passed does not compile to a valid regex, an E_WARNING is emitted. // // [examples] // Examples // [example] // Example #1 preg_split() example : Get the parts of a search string // [php] // // split the phrase by any number of commas or space characters, // // which include " ", \r, \t, \n and \f // $keywords = preg_split("/[\s,]+/", "hypertext language, programming"); // print_r($keywords); // [/php] // The above example will output: // [result] // Array // ( // [0] => hypertext // [1] => language // [2] => programming // ) // [/result] // [/example] // [example] // Example #2 Splitting a string into component characters // [php] // $str = 'string'; // $chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY); // print_r($chars); // [/php] // The above example will output: // [result] // Array // ( // [0] => s // [1] => t // [2] => r // [3] => i // [4] => n // [5] => g // ) // [/result] // [/example] // [example] // Example #3 Splitting a string into matches and their offsets // [php] // $str = 'hypertext language programming'; // $chars = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE); // print_r($chars); // [/php] // The above example will output: // [result] // Array // ( // [0] => Array // ( // [0] => hypertext // [1] => 0 // ) // // [1] => Array // ( // [0] => language // [1] => 10 // ) // // [2] => Array // ( // [0] => programming // [1] => 19 // ) // // ) // [/result] // [/example] // [/examples] // // Notes // Tip: If you don't need the power of regular expressions, you can choose faster (albeit simpler) alternatives like explode() or str_split(). // Tip: If matching fails, an array with a single element containing the input string will be returned. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-15) // URL: https://www.php.net/manual/en/function.preg-split.php // ========== PREG_SPLIT - END // SYNTAX: // array|false preg_split(string $pattern, string $subject, int $limit = -1, int $flags = 0) return $return_preg_split; // array|false } // ============================== END // PHP_TEXT_PCRE_PREG_SPLIT // ============================== // ============================== END // PHP_TEXT_PCRE // ============================== ?>