6、正则表达式
2017-09-28 本文已影响0人
hello大象



模式修正符:i 忽略大小写 g 全局匹配

特别字符



比较重要的两个方面:

preg_replace — 执行一个正则表达式的搜索和替换,搜索subject中匹配pattern的部分, 以replacement进行替换。
preg_replace ( pattern ,replacement , $subject )
返回值:
如果subject是一个数组, preg_replace()返回一个数组, 其他情况下返回一个字符串。
如果匹配被查找到,替换后的subject被返回,其他情况下 返回没有改变的 subject。如果发生错误,返回 NULL 。

关于php的贪婪模式详解
.* 是贪婪模式 .*? 取消贪婪模式。




preg_match():preg_match — 执行一个正则表达式匹配
int preg_match( string pattern, string subject [, array matches ] )
pattern:正则表达式
subject:需要匹配检索的对象
matches:可选,存储匹配结果的数组, $matches[0] 将包含与整个模式匹配的文本,$matches[1] 将包含与第一个捕获的括号中的子模式所匹配的文本,以此类推
preg_match_all() 函数用于进行正则表达式全局匹配,成功返回整个模式匹配的次数(可能为零),如果出错返回 FALSE 。
preg_replace — 执行一个正则表达式的搜索和替换
preg_match() 返回 pattern 所匹配的次数。要么是 0 次(没有匹配)或 1 次,因为 preg_match() 在第一次匹配之后将停止搜索。preg_match_all() 则相反,会一直搜索到 subject 的结尾处。如果出错 preg_match() 返回 FALSE。
mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
搜索subject中匹配pattern的部分, 以replacement进行替换。
preg_split — 通过一个正则表达式分隔字符串
array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )
eg:
<?php
//使用逗号或空格(包含" ", \r, \t, \n, \f)分隔短语
$keywords = preg_split ( "/[\s,]+/" , "hypertext language, programming" );
print_r ( $keywords );
?>
输出:
Array
(
[0] => hypertext
[1] => language
[2] => programming
)



<?php
$str = '中文';
//匹配utf8
//$pattern = '/[\x{4e00}-\x{9fa5}]/u';
//匹配GB2312
//$pattern = '/['.chr(0xb0).'-'.chr(0xf7).']['.chr(0xa1).'-'.chr(0xfe).']/';
preg_match($pattern, $str, $match);
var_dump($match);









<img.*?src=["|'](.*?)["|'].*?\/?>
.*?a
就是取前面任意长度的字符,到底一个 a 出现,匹配如下
q@wer_qwerqweraljlkjlkjlkj
得到:q@wer_qwerqwera 这部分,如果匹配不到后面的 a 字符,则匹配为空。
匹配URL:
邮箱:
<?php
$str = "cheng@163.com";
$pattern = '/^\w{5,15}@[a-z0-9]+(\.[a-z]+)+$/';
preg_match($pattern,$str,$match);
print_r($match);

ip地址:
//匹配ip地址:
$str = "192.56.20.253";
$pattern = '/^([1-9]|[1-9]\d|1\d\d|2[01]\d|22[0-3])(\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])){3}$/';
preg_match($pattern,$str,$match);
print_r($match);

参考github