模式修饰符

下面列出了当前可用的 PCRE 修饰符。括号中提到的名字是 PCRE 内部这些修饰符的名称。 模式修饰符中的空格,换行符会被忽略,其他字符会导致错误。

i (PCRE_CASELESS)

  如果设置了这个修饰符,模式中的字母会进行大小写不敏感匹配。

m (PCRE_MULTILINE)

  默认情况下,PCRE 认为目标字符串是由单行字符组成的(然而实际上它可能会包含多行), "行首"元字符 (^) 仅匹配字符串的开始位置, 而"行末"元字符 ($) 仅匹配字符串末尾, 或者最后的换行符(除非设置了 D 修饰符)。这个行为和 perl 相同。 当这个修饰符设置之后,“行首”和“行末”就会匹配目标字符串中任意换行符之前或之后,另外, 还分别匹配目标字符串的最开始和最末尾位置。这等同于 perl 的 /m 修饰符。如果目标字符串 中没有 "\n" 字符,或者模式中没有出现 ^ 或 $,设置这个修饰符不产生任何影响。

s (PCRE_DOTALL)

  如果设置了这个修饰符,模式中的点号元字符匹配所有字符,包含换行符。如果没有这个 修饰符,点号不匹配换行符。这个修饰符等同于 perl 中的/s修饰符。 一个取反字符类比如 [^a] 总是匹配换行符,而不依赖于这个修饰符的设置。

x (PCRE_EXTENDED)

  如果设置了这个修饰符,模式中的没有经过转义的或不在字符类中的空白数据字符总会被忽略, 并且位于一个未转义的字符类外部的#字符和下一个换行符之间的字符也被忽略。 这个修饰符 等同于 perl 中的 /x 修饰符,使被编译模式中可以包含注释。 注意:这仅用于数据字符。 空白字符 还是不能在模式的特殊字符序列中出现,比如序列 (?( 引入了一个条件子组(译注: 这种语法定义的 特殊字符序列中如果出现空白字符会导致编译错误。 比如(?(就会导致错误)。

e (PREG_REPLACE_EVAL)

Warning

本特性已自 PHP 5.5.0 起废弃。强烈建议不要使用本特性。

如果设置了这个被弃用的修饰符, preg_replace() 在进行了对替换字符串的 后向引用替换之后, 将替换后的字符串作为php 代码评估执行(eval 函数方式),并使用执行结果 作为实际参与替换的字符串。单引号、双引号、反斜线(\)和 NULL 字符在 后向引用替换时会被用反斜线转义.

Caution

The addslashes() function is run on each matched backreference before the substitution takes place. As such, when the backreference is used as a quoted string, escaped characters will be converted to literals. However, characters which are escaped, which would normally not be converted, will retain their slashes. This makes use of this modifier very complicated.

Caution

请确保 replacement 参数由合法 php 代码字符串组成,否则 php 将会 在preg_replace() 调用的行上产生一个解释错误。

Caution

Use of this modifier is discouraged, as it can easily introduce security vulnerabilites:

<?php
$html = $_POST['html'];

// uppercase headings
$html = preg_replace(
    '(<h([1-6])>(.*?)</h\1>)e',
    '"<h$1>" . strtoupper("$2") . "</h$1>"',
    $html
);

The above example code can be easily exploited by passing in a string such as <h1>{${eval($_GET[php_code])}}</h1>. This gives the attacker the ability to execute arbitrary PHP code and as such gives him nearly complete access to your server.

To prevent this kind of remote code execution vulnerability the preg_replace_callback() function should be used instead:

<?php
$html = $_POST['html'];

// uppercase headings
$html = preg_replace_callback(
    '(<h([1-6])>(.*?)</h\1>)',
    function ($m) {
        return "<h$m[1]>" . strtoupper($m[2]) . "</h$m[1]>";
    },
    $html
);

Note:

仅 preg_replace() 使用此修饰符,其他 PCRE 函数忽略此修饰符。

A (PCRE_ANCHORED)如果设置了这个修饰符,模式被强制为"锚定"模式,也就是说约束匹配使其仅从 目标字符串的开始位置搜索。这个效果同样可以使用适当的模式构造出来,并且 这也是 perl 种实现这种模式的唯一途径。D (PCRE_DOLLAR_ENDONLY)如果这个修饰符被设置,模式中的元字符美元符号仅仅匹配目标字符串的末尾。如果这个修饰符 没有设置,当字符串以一个换行符结尾时, 美元符号还会匹配该换行符(但不会匹配之前的任何换行符)。 如果设置了修饰符m,这个修饰符被忽略. 在 perl 中没有与此修饰符等同的修饰符。S当一个模式需要多次使用的时候,为了得到匹配速度的提升,值得花费一些时间 对其进行一些额外的分析。如果设置了这个修饰符,这个额外的分析就会执行。当前, 这种对一个模式的分析仅仅适用于非锚定模式的匹配(即没有单独的固定开始字符)。U (PCRE_UNGREEDY)这个修饰符逆转了量词的"贪婪"模式。 使量词默认为非贪婪的,通过量词后紧跟? 的方式可以使其成为贪婪的。这和 perl 是不兼容的。 它同样可以使用 模式内修饰符设置 (?U)进行设置, 或者在量词后以问号标记其非贪婪(比如.*?)。

Note:

在非贪婪模式,通常不能匹配超过 pcre.backtrack_limit 的字符。

X (PCRE_EXTRA)这个修饰符打开了 PCRE 与 perl 不兼容的附件功能。模式中的任意反斜线后就 ingen 一个 没有特殊含义的字符都会导致一个错误,以此保留这些字符以保证向后兼容性。 默认情况下,在 perl 中,反斜线紧跟一个没有特殊含义的字符被认为是该字符的原文。 当前没有其他特性由这个修饰符控制。J (PCRE_INFO_JCHANGED)内部选项设置(?J)修改本地的PCRE_DUPNAMES选项。允许子组重名, (译注:只能通过内部选项设置,外部的 /J 设置会产生错误。)u (PCRE_UTF8)此修正符打开一个与 perl 不兼容的附加功能。 模式字符串被认为是utf-8的. 这个修饰符 从 unix 版php 4.1.0 或更高,win32版 php 4.2.3 开始可用。 php 4.3.5 开始检查模式的 utf-8 合法性。

 add a note

User Contributed Notes 6 notes

22

hfuecks at nospam dot org

11 years ago
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";
    }
    
}
?>
9

phpman at crustynet dot org dot uk

5 years ago
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]
8

Daniel Klein

4 years ago
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.
6

michal dot kocarek at brainbox dot cz

7 years ago
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.
4

varrah NO_GARBAGE_OR_SPAM AT mail DOT ru

11 years ago
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.
4

ebarnard at marathonmultimedia dot com

9 years ago
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
 
 
 
 
 
原文链接:http://php.net/manual/zh/reference.pcre.pattern.modifiers.php
 

PHP正则表达式模式修饰符 /i, /is, /s, /isU等的更多相关文章

  1. PHP正则表达式模式修饰符详解

    PHP模式修饰符又叫模式修正符,是在正则表达式的定界符之外使用.主要用来调整正则表达式的解释,提扩展了正则表达式在匹配.替换等操作的某些功能,增强了正则的能力.但是有很多地方的解释都是错误的,也容易误 ...

  2. 关于php正则表达式模式修饰符

    一直以来,以为自己的正则表达式学的还算可以(基本工作上遇到的问题都能解决),但有时候却是知其然而不知其所以然,在网上看到这篇文章,解释了之前的很多疑问,记录下来,随时温故而知新. i (PCRE_CA ...

  3. PHP中 PCRE正则表达式模式修饰符“u” 的使用。

    u (PCRE_UTF8) 此修正符打开一个与 perl 不兼容的附加功能. 模式字符串被认为是utf-8的. 这个修饰符 从 unix 版php 4.1.0 或更高,win32版 php 4.2.3 ...

  4. Mongoose 预定义模式修饰符 Getters 与 Setters 自定义修饰符

    mongoose 预定义模式修饰符 mongoose 提供的预定义模式修饰符,可以对我们增加的数据进行一些格式化,主要有:lowercase.uppercase .trim,这里不一一演示,对trim ...

  5. 正则表达式模式修正符 比如/esi

    正则表达式模式修正符 比如/esi 作者: 字体:[增加 减小] 类型:转载 下面列出了当前在 PCRE 中可能使用的修正符.括号中是这些修正符的内部 PCRE 名.修正符中的空格和换行被忽略,其它字 ...

  6. PHP正则表达式 /i, /s, /x,/u, /U, /A, /D, /S等模式修饰符

    i (PCRE_CASELESS) 如果设置了这个修饰符, 模式中的字母会进行大小写不敏感匹配. m (PCRE_MULTILINE) 默认情况下, PCRE认为目标字符串是由单行字符组成的(然而实际 ...

  7. python正则表达式--flag修饰符、match对象属性

    正则表达式—修饰符 正则表达式可以包含一些标志修饰符来控制匹配模式,用在正则表达式处理函数中的flag参数中,为可选参数. (1) re.I 全写(re.IGNORECASE) 表示使匹配时,忽略大小 ...

  8. PHP 正则表达式 修饰符

    下面列出了当前可用的 PCRE 修饰符.括号中提到的名字是 PCRE 内部这些修饰符的名称. 模式修饰符中的空格,换行符会被忽略,其他字符会导致错误. i (PCRE_CASELESS) 如果设置了这 ...

  9. i 是一个修饰符 (搜索不区分大小写)

    什么是正则表达式? 正则表达式是由一个字符序列形成的搜索模式. 当你在文本中搜索数据时,你可以用搜索模式来描述你要查询的内容. 正则表达式可以是一个简单的字符,或一个更复杂的模式. 正则表达式可用于所 ...

随机推荐

  1. 在树莓派(Raspberry Pi)上编译安装更新版本的Python

    Raspiban Wheezy上预装的Python3版本是3.2.3,本文将介绍升级到3.4.3的方法. 此文也适用于安装其它版本(比如最新版本)的Python. 我用的是B+型的树莓派,装的系统是2 ...

  2. ie的不同版本测试

    ie的11.0.9600.17728版本支持在开发者工具栏中导航中edge按钮支持测试在不同ie版本下的显示情况如ie7,8,9但不支持ie6

  3. CDN 技术详解(DNS,GSLB,Cache)

    CDN 是什么 CDN(Content Delivery Network,内容分发网络),即全网内容加速服务.为了尽可能的避开互联网上有可能影响数据传输速度和稳定性的瓶颈和环节,使内容传输的更快.更稳 ...

  4. LeetCode---Stack && Heap

    402. Remove K Digits 思路:一次判断字符若比栈顶字符大则入栈,若小则pop,同时k--,直到k为0,注意最终k没有减为0或者中途栈为空或者最终结果前面带0的情况 public St ...

  5. ubuntu12.10 源更新出错(sudo apt-get update)

    Ubuntu12.10 刚安装完发现vi编辑器无法正常使用,后来用sudo apt-get install vim 一直出错,搜索相关资源发现需要更新源 首先,备份一下Ubuntu 12.10 原来的 ...

  6. stl::map之const函数访问

    如何在const成员数中访问stl::map呢?例如如下代码: string ConfigFileManager::MapQueryItem(const string& name) const ...

  7. SQL:安装多个实例,修改实例端口号,和IP加端口号连接实例

    sql server 安装第一个实例,默认实例的端口是1433, 一个库中如果有多个实例,从第二个实例开始的端口是动态端口,需要的话,自己手工指定为静态端口,如指定第二个实例为1434 或着随意一个如 ...

  8. 一款好用且免费的语句分析工具Plan Explorer

    在调优过程中的查询语句优化阶段,分析语句的执行计划是必经之路,一款好的执行计划分析工具确实可以帮助我们事半功倍 小贴士:Plan Explorer是将Plan Explorer 专业版与免费版整合在一 ...

  9. Discrete.Differential.Geometry-An.Applied.Introduction(sig2008)笔记

    -------------------------------------------------------------- Chapter 1: Introduction to Discrete D ...

  10. 用PHP+MySQL来做分页的演示

    用php做分页弄懂逻辑关系其实不难,不过我在听课的时候估计是被老师讲的那些变量里的英文单词给听懵了,因为有几个变量的名字都很像,只是换了两三个英文字母而已,有的就少几个这样的,听到一半已经不知道老师讲 ...