downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

PCRE regex syntax> <Padrões PCRE
Last updated: Fri, 13 Nov 2009

view this page in

Modificadores do Padrão

Os atuais possíveis modificadores PCRE são listados abaixo. Os nomes entre parênteses referem-se ao nome interno destes modificadores. Espaço e newlines são ignorado nos modificadores, outros caracteres causam erro.

i (PCRE_CASELESS)
Se este modificador é usado, as letras no padrão combinam tanto maiúsculas quanto minúsculas.
m (PCRE_MULTILINE)
Por padrão, PCRE trata a string alvo como consistindo de uma única linha de caracteres (mesmo se ele realmente contêm vários newlines). O metacaractere "ínicio da linha" (^) combina somente no início da string, quando o metacaractere "fim da linha" combina somente no final da string, ou antes de um newline no fim (a menos que o modificador D seja usado). Este é o mesmo do Perl. Quando este modificador é usado, os construtores "início da linha" e "final de linha" combinam logo depois ou logo antes de algum newline na string alvo, respectivamente, bem como no começo e fim. Isto é equivalente ao modificador /m do Perl. Se não houver um caractere "\n" na string alvo, ou nenhum ocorrência do ^ ou $ no padrão, usar este modificador não tem efeito.
s (PCRE_DOTALL)
Se este modificador é usado, um metacaractere ponto no padrão combina todos caracteres, incluindo newlines. Sem ele, newlines são excluídos. Este modificador é equivalente ao modificador /s do Perl. Uma classe negada como [^a] sempre combina um caractere newline, independente do uso deste modificador.
x (PCRE_EXTENDED)
Se este modificador é usado, caracteres whitespace no padrão são totalmente ignorado exceto quando escapado ou dentro de um classe de caractere, e inclusive caracteres entre um # não precedido de escape fora de uma classe de caracteres e o próximo caractere newline, são também ignorados. Este é equivalente ao modificador /x do Perl, tornando possível incluir comentários dentro de padrões complicados. Note, contudo, que isto é aplicado somente a caracteres de dados. Caracteres whitespace nunca podem aparecer dentro de especial sequência de caracteres no padrão, por exemplo na sequência (?( que introduz um subpadrão condicional.
e (PREG_REPLACE_EVAL)
Se este modificador é usado, preg_replace() faz a normal substituição de backreferences na string substituta, avaliando-a como código PHP, e usando o resultado para trocar a string procurada. Aspas simples, aspas duplas, escape e caractere NULL terão escape nos backreferences.

Somente preg_replace() usa este modificador; ele é ignorado por outras funções PCRE.

A (PCRE_ANCHORED)
Se este modificador é usado, o padrão é forçado para ser "âncorado", isto é, ele restringido para combinar somente no início da string que está sendo procurada (a "string alvo"). Este efeito pode também ser alcançado pelo apropriado construtor no padrão, que é o única forma de fazer em Perl. 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)
Se este modificador é usado, o metacaractere dólar no padrão combina somente no final da string alvo. Sem este modificador, um dólar também combina imediatamente antes do caractere final se ele for um newline (mas não antes de outros newlines). Este modificador é ignorado se o modificador m é usado. Não há um equivalente a este modificador no Perl.
S
Quando um padrão será usado diversas vezes, vale a pena gastar mais tempo analisando em favor da velocidade a fim apressar a combinação. Se este modificador for usado, esta análise extra será executada. Atualmente, estudar um teste padrão é útil somente para os testes padrões não escorados, que não têm um único caracter inicial fixo.
U (PCRE_UNGREEDY)
Este modificador inverte a "gulosidade" dos quantificadores de modo que não sejam gulosos por padrão, mas torna-se guloso se seguido por "?". Não é compatível com Perl. Pode também ser usado por um (?U) que ajusta-se dentro do teste padrão ou por uma interrogação depois de um quantificador (por exemplo .*?).
X (PCRE_EXTRA)
Este modificador aciona uma funcionalidade adicional do PCRE que é incompatível com Perl. Qualquer barra invertida (backslash) na busca que é seguida por uma letra que não tenha nenhum significado especial causa um erro, reservando assim essas combinações para futuros upgrades. Até agora não há outra funcionalidade controlada por este modificador.
J (PCRE_INFO_JCHANGED)
A opção de configuração interna (?J) modifica a opção local PCRE_DUPNAMES. Que permite a duplicação de nomes de subpadrões.
u (PCRE_UTF8)
Este modificador aciona uma funcionalidade adicional de PCRE que é incompatível com Perl. As strings do padrão são tratadas como UTF-8. Este modificador está disponível no PHP 4.1.0 ou superior em Unix e no PHP 4.2.3 em WIN32. Validez do UTF-8 no padrão é verificado desde o PHP 4.3.5.



PCRE regex syntax> <Padrões PCRE
Last updated: Fri, 13 Nov 2009
 
add a note add a note User Contributed Notes
Descreve possíveis modificadores no padrão regex
michal dot kocarek at brainbox dot cz
18-May-2009 09:49
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.
ebarnard at marathonmultimedia dot com
06-Feb-2007 08:35
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
varrah NO_GARBAGE_OR_SPAM AT mail DOT ru
03-Nov-2005 10:12
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.
hfuecks at nospam dot org
15-Jul-2005 12:14
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";
    }
   
}
?>
csaba at alum dot mit dot edu
08-Apr-2005 10:40
Extracting lines of text:

You might want to grab a line of text within a multiline piece of text.  For example, suppose you want to replace the first and last lines within the <body> portion of a web $page with your own $lineFirst and $lineLast.  Here's one possible way:

<?php
$lineFirst
= "This is a new first line<br>\r\n";
$lineLast  = "This is a new last line<br>\r\n";
$page = <<<EOD
<html><head>
<title>This is a test page</title>
</head><body>
This is the first line<br>
Hi Fred<br>
Hi Bill<br>
This is the last line<br>
</body>
</html>
EOD;
$re = "/<body>.*^(.+)(^.*?^)(.+)(^<\\/body>.*?)/smU";
if (
preg_match($re, $page, $aMatch, PREG_OFFSET_CAPTURE))
$newPage = substr($text, 0, $aMatch[1][1]) .
          
$lineFirst . $aMatch[2][0] .
          
$lineLast . $aMatch[4][0];
print
$newPage;
?>

The two (.+) are supposed to match the first and last lines within the <body> tag.  The /s option (dot all) is needed so the .* can also match newlines.  The /m option (multiline) is needed so that the ^ can match newlines.  The /U option (ungreedy) is needed so that the .* and .+ will only gobble up the minimum number of characters necessary to get to the character following the * or +.  The exception to this, however, is that the .*? temporarily overrides the /U setting on .* turning it from non greedy to greedy.  In the middle, this ensures that all the lines except the first and last (within the <body> tag) are put into $aMatch[2].  At the end, it ensures that all the remaining characters in the string are gobbled up, which could also have been achieved by .*)\\z/ instead of .*?)/

Csaba Gabor from Vienna

PCRE regex syntax> <Padrões PCRE
Last updated: Fri, 13 Nov 2009
 
 
show source | credits | sitemap | contact | advertising | mirror sites