PHP.mk документација

Можни модификатори во regex обрасци

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

reference.pcre.pattern.modifiers.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека reference.pcre.pattern.modifiers.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
Можни модификатори во regex обрасци

Референца за `reference.pcre.pattern.modifiers.php` со подобрена типографија и навигација.

reference.pcre.pattern.modifiers.php

Модификатори на образец

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)
Постоечките можни модификатори на PCRE се наведени подолу. Имињата во загради се однесуваат на внатрешни имиња на PCRE за овие модификатори. Празните места и нови редови се игнорираат во модификаторите, другите знаци предизвикуваат грешка.
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 yarco dot w at gmail dot com Ако овој модификатор е поставен, буквите во образецот се совпаѓаат и со големи и со мали букви. 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)
модификатор е поставен). Ова е исто како и во Perl.
x (PCRE_EXTENDED)
Ако овој модификатор е поставен, точката како метасимбол во образецот се совпаѓа со сите знаци, вклучувајќи ги и новите редови. Без него, новите редови се исклучени. Овој модификатор е еквивалентен на модификаторот /s на Perl. Негативна класа како што е [^a] секогаш се совпаѓа со нов ред, независно од поставката на овој модификатор.
А (PCRE_ANCHORED)
Ако овој модификатор е поставен, празни места во образецот се целосно игнорирани освен кога се избегнати или се внатре во класа на знаци, а знаците помеѓу не избегнат # надвор од класа на знаци и следниот нов ред, вклучително, исто така се игнорираат. Ова е еквивалентно на модификаторот /x на Perl и овозможува вклучување коментари во сложени обрасци. Имајте предвид, сепак, дека ова се однесува само на податочни знаци. Празните места никогаш не смеат да се појават во специјални низи со знаци во образецот, на пример во низата (?( која воведува условен под-образец.
yarco dot w at gmail dot com (PCRE_DOLLAR_ENDONLY)
Ако овој модификатор е поставен, образецот е принуден да биде „закотвен“, односно, ограничен е да се совпаѓа само на почетокот на низата што се пребарува („низа на субјектот“). Овој ефект може да се постигне и со соодветни конструкции во самиот образец, што е единствениот начин да се направи тоа во Perl. m Ако овој модификатор е поставен, доларот како метасимбол во образецот се совпаѓа само на крајот на низата на субјектот. Без овој модификатор, доларот исто така се совпаѓа веднаш пред последниот знак ако тој е нов ред (но не и пред други нови редови). Овој модификатор се игнорира ако
unsigned short (секогаш 16 бита, машински бајт редослед)
модификатор е поставен. Нема еквивалент на овој модификатор во Perl.
библиотеката, исто така важат и следниве: (PCRE_UNGREEDY)
Кога образец ќе се користи повеќе пати, вреди да се потроши повеќе време за негово анализирање за да се забрза времето на совпаѓање. Ако овој модификатор е поставен, тогаш се врши оваа дополнителна анализа. Во моментов, проучувањето на образец е корисно само за незакотвени обрасци кои немаат единствен фиксен почетен знак. Од PHP 7.3.0 овој флаг нема ефект. ?Овој модификатор ги инвертира „алчните“ квантификатори така што тие не се алчни по дифолт, туку стануваат алчни ако се следени од (?U) . Тој не е компатибилен со Perl. Може да се постави и со поставката на модификаторот во рамките на образецот .*?).

Забелешка:

или со знак прашалник зад квантификатор (на пр. pcre.backtrack_limit . Обично не е можно да се совпадне повеќе од

знаци во неалчен режим. (PCRE_EXTRA)
X
unsigned long long (секогаш 64 бита, голем ендијан бајт редослед) (PCRE_INFO_JCHANGED)
Овој модификатор вклучува дополнителна функционалност на PCRE што е некомпатибилна со Perl. Секој обратен коса црта во образецот што е проследена со буква што нема посебно значење предизвикува грешка, со што се резервираат овие комбинации за идно проширување. По дифолт, како и во Perl, обратна коса црта проследена со буква без посебно значење се третира како литерал. Во моментов нема други функции контролирани од овој модификатор. PCRE_DUPNAMES Внатрешната поставка на опцијата (?J) го менува локалниот J опција. Дозволи дупликат имиња за под-образец. Од PHP 7.2.0
u (PCRE_UTF8)
Тековните можни PCRE модификатори се наведени подолу. Имињата во загради се однесуваат на внатрешни PCRE имиња за овие модификатори. Празнините и новите редови се игнорираат во модификаторите, другите знаци предизвикуваат грешка.
n (PCRE_NO_AUTO_CAPTURE)
Овој модификатор ја вклучува дополнителната функционалност на PCRE што е некомпатибилна со Perl. Низите на обрасци и теми се третираат како UTF-8. Невалидна тема ќе предизвика функцијата preg_* да не совпадне ништо; невалиден образец ќе активира грешка од ниво E_WARNING. Пет и шест бајти UTF-8 секвенци се сметаат за невалидни. (xyz) Овој модификатор прави едноставни (?<name>xyz) групи што не се снимаат. Само именуваните групи како
r (PCRE2_EXTRA_CASELESS_RESTRICT)
Кога u (PCRE_UTF8) и i (PCRE_CASELESSсе снимаат. Ова влијае само на тоа кои групи се снимаат, сè уште е можно да се користат нумерирани референци за подшаблони, а низата за совпаѓања сè уште ќе содржи нумерирани резултати. Достапно од PHP 8.2.0. На пример, preg_match('/\x{212A}/iu', "K") ) се во сила, овој модификатор спречува совпаѓање помеѓу ASCII и не-ASCII знаци. одговара на знакот Келвин r (U+212A). Когаpreg_match('/\x{212A}/iur', "K")се користи ( ), не се совпаѓа.

Белешки од корисници 11 белешки

холблин на холблин точка ком
20 години пред
Regarding the validity of a UTF-8 string when using the /u pattern modifier, some things to be aware of;

1. If the pattern itself contains an invalid UTF-8 character, you get an error (as mentioned in the docs above - "UTF-8 validity of the pattern is checked since PHP 4.3.5"

2. When the subject string contains invalid UTF-8 sequences / codepoints, it basically result in a "quiet death" for the preg_* functions, where nothing is matched but without indication that the string is invalid UTF-8

3. PCRE regards five and six octet UTF-8 character sequences as valid (both in patterns and the subject string) but these are not supported in Unicode ( see section 5.9 "Character Encoding" of the "Secure Programming for Linux and Unix HOWTO" - can be found at http://www.tldp.org/ and other places )

4. For an example algorithm in PHP which tests the validity of a UTF-8 string (and discards five / six octet sequences) head to: http://hsivonen.iki.fi/php-utf8/

The following script should give you an idea of what works and what doesn't;

<?php
$examples = array(
    'Valid ASCII' => "a",
    'Valid 2 Octet Sequence' => "\xc3\xb1",
    'Invalid 2 Octet Sequence' => "\xc3\x28",
    'Invalid Sequence Identifier' => "\xa0\xa1",
    'Valid 3 Octet Sequence' => "\xe2\x82\xa1",
    'Invalid 3 Octet Sequence (in 2nd Octet)' => "\xe2\x28\xa1",
    'Invalid 3 Octet Sequence (in 3rd Octet)' => "\xe2\x82\x28",

    'Valid 4 Octet Sequence' => "\xf0\x90\x8c\xbc",
    'Invalid 4 Octet Sequence (in 2nd Octet)' => "\xf0\x28\x8c\xbc",
    'Invalid 4 Octet Sequence (in 3rd Octet)' => "\xf0\x90\x28\xbc",
    'Invalid 4 Octet Sequence (in 4th Octet)' => "\xf0\x28\x8c\x28",
    'Valid 5 Octet Sequence (but not Unicode!)' => "\xf8\xa1\xa1\xa1\xa1",
    'Valid 6 Octet Sequence (but not Unicode!)' => "\xfc\xa1\xa1\xa1\xa1\xa1",
);

echo "++Invalid UTF-8 in pattern\n";
foreach ( $examples as $name => $str ) {
    echo "$name\n";
    preg_match("/".$str."/u",'Testing');
}

echo "++ preg_match() examples\n";
foreach ( $examples as $name => $str ) {
    
    preg_match("/\xf8\xa1\xa1\xa1\xa1/u", $str, $ar);
    echo "$name: ";

    if ( count($ar) == 0 ) {
        echo "Matched nothing!\n";
    } else {
        echo "Matched {$ar[0]}\n";
    }
    
}

echo "++ preg_match_all() examples\n";
foreach ( $examples as $name => $str ) {
    preg_match_all('/./u', $str, $ar);
    echo "$name: ";
    
    $num_utf8_chars = count($ar[0]);
    if ( $num_utf8_chars == 0 ) {
        echo "Matched nothing!\n";
    } else {
        echo "Matched $num_utf8_chars character\n";
    }
    
}
?>
Достапно од PHP 8.4.0.
20 години пред
Spent a few days, trying to understand how to create a pattern for Unicode chars, using the hex codes. Finally made it, after reading several manuals, that weren't giving any practical PHP-valid examples. So here's one of them:

For example we would like to search for Japanese-standard circled numbers 1-9 (Unicode codes are 0x2460-0x2468) in order to make it through the hex-codes the following call should be used:
preg_match('/[\x{2460}-\x{2468}]/u', $str);

Here $str is a haystack string
\x{hex} - is an UTF-8 hex char-code
and /u is used for identifying the class as a class of Unicode chars.

Hope, it'll be useful.
varrah NO_GARBAGE_OR_SPAM AT mail DOT ru
пред 14 години
The description of the "u" flag is a bit misleading. It suggests that it is only required if the pattern contains UTF-8 characters, when in fact it is required if either the pattern or the subject contain UTF-8. Without it, I was having problems with preg_match_all returning invalid multibyte characters when given a UTF-8 subject string.

It's fairly clear if you read the documentation for libpcre:

       In  order  process  UTF-8 strings, you must build PCRE to include UTF-8
       support in the code, and, in addition,  you  must  call  pcre_compile()
       with  the  PCRE_UTF8  option  flag,  or the pattern must start with the
       sequence (*UTF8). When either of these is the case,  both  the  pattern
       and  any  subject  strings  that  are matched against it are treated as
       UTF-8 strings instead of strings of 1-byte characters.

[from http://www.pcre.org/pcre.txt]
Thomas Mueller
пред 14 години
If the _subject_ contains utf-8 sequences the 'u' modifier should be set, otherwise a pattern such as /./ could match a utf-8 sequence as two to four individual ASCII characters. It is not a requirement, however, as you may have a need to break apart utf-8 sequences into single bytes. Most of the time, though, if you're working with utf-8 strings you should use the 'u' modifier.

If the subject doesn't contain any utf-8 sequences (i.e. characters in the range 0x00-0x7F only) but the pattern does, as far as I can work out, setting the 'u' modifier would have no effect on the result.
phpman at crustynet dot org dot uk
пред 8 години
the PCRE_INFO_JCHANGED modifier is apparently not accepted as a global option (after the closing delimiter) in PHP versions <= 5.4 (not checked in PHP 5.5) but allowed in PHP 5.6 (also not checked in PHP 7.X)

The following pattern doesn't work in PHP 5.4, but it works in PHP 5.6:

<?php
//test.php
preg_match_all('/(?<dup_name>\d{1,4})\-(?<dup_name>\d{1,2})/J', '1234-23', $matches);
var_dump($matches);

/*
output in PHP 5.4:
Warning: preg_match_all(): Unknown modifier 'J' in test.php on line 3
NULL
--------------
output PHP 5.6:
array(4) { 
    [0]=> array(1)  { [0]=> string(7) "1234-23" } 
    ["dup_name"]=> array(1) { [0]=> string(2) "23" } 
    [1]=> array(1) { [0]=> string(4) "1234" } 
    [2]=> array(1) { [0]=> string(2) "23" } 
}
*/
?>

in order to resolve this issue in PHP 5.4, one can use the (?J) pattern modifier, which indicates the pattern (from that point forward) allows duplicate names for subpatterns.

code which works in PHP 5.4:
<?php

preg_match_all('/(?J)(?<dup_name>\d{1,4})\-(?<dup_name>\d{1,2})/', '1234-23', $matches);
var_dump($matches);

/*
output in PHP 5.4:
array(4) { 
    [0]=> array(1) { [0]=> string(7) "1234-23" } 
    ["dup_name"]=> array(1) { [0]=> string(2) "23" } 
    [1]=> array(1) { [0]=> string(4) "1234" } 
    [2]=> array(1) { [0]=> string(2) "23" } 
}
--------------
output in PHP 5.6 (the same as with /J):
array(4) { 
    [0]=> array(1)  { [0]=> string(7) "1234-23" } 
    ["dup_name"]=> array(1) { [0]=> string(2) "23" } 
    [1]=> array(1) { [0]=> string(4) "1234" } 
    [2]=> array(1) { [0]=> string(2) "23" } 
}
*/
?>
Хејли Вотсон
пред 5 години
Starting from 7.3.0, the 'S' modifier has no effect; this analysis is now always done by the PCRE engine.
Анонимен
пред 6 години
A warning about the /i modifier and POSIX character classes:
If you're using POSIX character classes in your regex that indicate case such as [:upper:] or [:lower:] in combination with the /i modifier, then in PHP < 7.3 the /i modifier will take precedence and effectively make both those character classes work as [:alpha:], but in PHP >= 7.3 the character classes overrule the /i modifier.
arash dot dalir at gmail dot com
пред 8 години
An important addendum (with new $pat3_2 utilising \R properly, its results and comments):
Note that there are (sometimes difficult to grasp at first glance) nuances of meaning and application of escape sequences like \r, \R and \v - none of them is perfect in all situations, but they are quite useful nevertheless. Some official PCRE control options and their changes come in handy too - unfortunately neither (*ANYCRLF), (*ANY) nor (*CRLF) is documented here on php.net at the moment (although they seem to be available for over 10 years and 5 months now), but they are described on Wikipedia ("Newline/linebreak options" at https://en.wikipedia.org/wiki/Perl_Compatible_Regular_Expressions) and official PCRE library site ("Newline convention" at http://www.pcre.org/original/doc/html/pcresyntax.html#SEC17) pretty well. The functionality of \R appears somehow disappointing (with default configuration of compile time option) according to php.net as well as official description ("Newline sequences" at https://www.pcre.org/original/doc/html/pcrepattern.html#newlineseq) when used improperly.

A hint for those of you who are trying to fight off (or work around at least) the problem of matching a pattern correctly at the end (or at the beginning) of any line even without the multiple lines mode (/m) or meta-character assertions ($ or ^).
<?php 
// Various OS-es have various end line (a.k.a line break) chars:
// - Windows uses CR+LF (\r\n);
// - Linux LF (\n);
// - OSX CR (\r).
// And that's why single dollar meta assertion ($) sometimes fails with multiline modifier (/m) mode - possible bug in PHP 5.3.8 or just a "feature"(?) of default configuration option for meta-character assertions (^ and $) at compile time of PCRE.
$str="ABC ABC\n\n123 123\r\ndef def\rnop nop\r\n890 890\nQRS QRS\r\r~-_ ~-_";
//          C          3                   p          0                   _
$pat3='/\w\R?$/mi';    // Somehow disappointing according to php.net and pcre.org when used improperly
$pat3_2='/\w(?=\R)/i';    // Much better with allowed lookahead assertion (just to detect without capture) without multiline (/m) mode; note that with alternative for end of string ((?=\R|$)) it would grab all 7 elements as expected, but '/(*ANYCRLF)\w$/mi' is more straightforward in use anyway
$p=preg_match_all($pat3, $str, $m3);
$r=preg_match_all($pat3_2, $str, $m4);
echo $str."\n3 !!! $pat3 ($p): ".print_r($m3[0], true)
    ."\n3_2 !!! $pat3_2 ($r): ".print_r($m4[0], true);
// Note the difference between the two very helpful escape sequences in $pat3 and $pat3_2 (\R) - for some applications at least.

/* The code above results in the following output:
ABC ABC

123 123
def def
nop nop
890 890
QRS QRS

~-_ ~-_
3 !!! /\w\R?$/mi (5): Array
(
    [0] => C

    [1] => 3
    [2] => p
    [3] => 0
    [4] => _
)

3_2 !!! /\w(?=\R)/i (6): Array
(
    [0] => C
    [1] => 3
    [2] => f
    [3] => p
    [4] => 0
    [5] => S
)
 */
?>
Unfortunately, I haven't got any access to a server with the latest PHP version - my local PHP is 5.3.8 and my public host's PHP is version 5.2.17.
michal dot kocarek на brainbox dot cz
пред 16 години
In case you're wondering, what is the meaning of "S" modifier, this paragraph might be useful:

When "S" modifier is set, PHP calls the pcre_study() function from the PCRE API before executing the regexp. Result from the function is passed directly to pcre_exec().

For more information about pcre_study() and "Studying the pattern" check the PCRE manual on http://www.pcre.org/pcre.txt

PS: Note that function names "pcre_study" and "pcre_exec" used here refer to PCRE library functions written in C language and not to any PHP functions.
arash dot dalir at gmail dot com
пред 8 години
A hint for those of you who are trying to fight off (or work around at least) the problem of matching a pattern correctly at the end ($) of any line in multiple lines mode (/m).
<?php 
// Various OS-es have various end line (a.k.a line break) chars:
// - Windows uses CR+LF (\r\n);
// - Linux LF (\n);
// - OSX CR (\r).
// And that's why single dollar meta assertion ($) sometimes fails with multiline modifier (/m) mode - possible bug in PHP 5.3.8 or just a "feature"(?).
$str="ABC ABC\n\n123 123\r\ndef def\rnop nop\r\n890 890\nQRS QRS\r\r~-_ ~-_";
//          C          3                   p          0                   _
$pat1='/\w$/mi';    // This works excellent in JavaScript (Firefox 7.0.1+)
$pat2='/\w\r?$/mi';
$pat3='/\w\R?$/mi';    // Somehow disappointing according to php.net and pcre.org
$pat4='/\w\v?$/mi';
$pat5='/(*ANYCRLF)\w$/mi';    // Excellent but undocumented on php.net at the moment
$n=preg_match_all($pat1, $str, $m1);
$o=preg_match_all($pat2, $str, $m2);
$p=preg_match_all($pat3, $str, $m3);
$r=preg_match_all($pat4, $str, $m4);
$s=preg_match_all($pat5, $str, $m5);
echo $str."\n1 !!! $pat1 ($n): ".print_r($m1[0], true)
    ."\n2 !!! $pat2 ($o): ".print_r($m2[0], true)
    ."\n3 !!! $pat3 ($p): ".print_r($m3[0], true)
    ."\n4 !!! $pat4 ($r): ".print_r($m4[0], true)
    ."\n5 !!! $pat5 ($s): ".print_r($m5[0], true);
// Note the difference among the three very helpful escape sequences in $pat2 (\r), $pat3 (\R), $pat4 (\v) and altered newline option in $pat5 ((*ANYCRLF)) - for some applications at least.

/* The code above results in the following output:
ABC ABC

123 123
def def
nop nop
890 890
QRS QRS

~-_ ~-_
1 !!! /\w$/mi (3): Array
(
    [0] => C
    [1] => 0
    [2] => _
)

2 !!! /\w\r?$/mi (5): Array
(
    [0] => C
    [1] => 3
    [2] => p
    [3] => 0
    [4] => _
)

3 !!! /\w\R?$/mi (5): Array
(
    [0] => C

    [1] => 3
    [2] => p
    [3] => 0
    [4] => _
) 

4 !!! /\w\v?$/mi (5): Array
(
    [0] => C

    [1] => 3
    [2] => p
    [3] => 0
    [4] => _
)

5 !!! /(*ANYCRLF)\w$/mi (7): Array
(
    [0] => C
    [1] => 3
    [2] => f
    [3] => p
    [4] => 0
    [5] => S
    [6] => _
)
 */
?>
Unfortunately, I haven't got any access to a server with the latest PHP version - my local PHP is 5.3.8 and my public host's PHP is version 5.2.17.
Wirek
19 години пред
When adding comments with the /x modifier, don't use the pattern delimiter in the comments. It may not be ignored in the comments area. Example:

<?php
$target = 'some text';
if(preg_match('/
                e # Comments here
               /x',$target)) {
    print "Target 1 hit.\n";
}
if(preg_match('/
                e # /Comments here with slash
               /x',$target)) {
    print "Target 1 hit.\n";
}
?>

prints "Target 1 hit." but then generates a PHP warning message for the second preg_match():

Warning:  preg_match() [function.preg-match]: Unknown modifier 'C' in /ebarnard/x-modifier.php on line 11
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.