PHP正则表达式
0x00
在这里对PHP中Perl风格的正则表达式函数做一个分类总结.
在这里我们做如下约定:
- $pattern*=正则表达式
- $subject=匹配的目标数据
0x01
- preg_match()
函数原型:
int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )
该函数的返回值是0或者1,如果提供了参数matches那么它将会被填充为匹配到的文本。该函数是最多匹配一次。
- preg_match_all()
函数原型:
int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] )
该函数的返回值是匹配的返回次数,并且它会匹配所有的结果。
注意这两个函数的 array∗都是引用传递,直接修改∗ matches的值。
0x02
- preg_replace()
该函数的函数原型:
mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
返回替换的字符串
- preg_filter
该函数的原型:
mixed preg_filter ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
也是返回替换后的字符串。
两者的区别在于,preg_replace在替换数组的情况无论有没有匹配都会保留数组中的元素,而preg_filter只会保留数组中被替换了的元素。
0x03
- preg_grep
它是被大大简化的preg_filter,它只匹配,不替换。它把数组中不能被匹配的都过滤掉。
0x04
- preg_split
函数原型:
array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )
该函数会把匹配到的地方作为分割点将字符串分割后存入返回数组中。
0x05
- preg_quote
该函数可以把正则表达式中的特殊字符(. \ + ? [ ^ ] $ ( ) { } = ! < > | : -*)进行转译。
0x06正则表达式修正模式
未规定修正模式的时候自动是贪婪模式。
$pattern = '/\d/U'
这样就是懒惰模式。
那些常见的修正模式:
- U-懒惰匹配
- i-忽略英文字母大小写
- x-忽略空白
- s-让元字符’.’匹配换行符在内的所有字符