PHP PCRE 函数

# preg_filter — 执行一个正则表达式搜索和替换
preg_grep — 返回匹配模式的数组条目
# preg_last_error — 返回最后一个PCRE正则执行产生的错误代码
preg_match_all — 执行一个全局正则表达式匹配
preg_match — 执行匹配正则表达式
# preg_quote — 转义正则表达式字符
# preg_replace_callback_array — Perform a regular expression search and replace using callbacks
preg_replace_callback — 执行一个正则表达式搜索并且使用一个回调进行替换
preg_replace — 执行一个正则表达式的搜索和替换
preg_split — 通过一个正则表达式分隔字符串

手册地址:https://www.php.net/manual/zh/ref.pcre.php

模式修饰符
https://www.php.net/manual/zh/reference.pcre.pattern.modifiers.php

preg_grep
$arr = [1, 'a', '2', 'e', 3];
$preg = '/d/';
$arr = preg_grep($preg, $arr);

/*
Array
(
    [0] => 1
    [2] => 2
    [4] => 3
)
*/

preg_match && preg_match_all

preg_match : preg_match()在第一次匹配后 将会停止搜索
preg_match_all : 在第一个匹配找到后, 子序列继续从最后一次匹配位置搜索

// 加深贪婪模式印象
$td = '<td>td1 content</td><td>td2 content</td>';
$tdRegx1 = '/<td>(.*)</td>/';
preg_match($tdRegx1, $td, $tdMatch);
/*
Array
(
    [0] => <td>td1 content</td><td>td2 content</td>
    [1] => td1 content</td><td>td2 content
)
*/

$tdRegx2 = '/<td>(.*)</td>/U';
// $tdRegx1 = '/<td>(.*?)</td>/';
preg_match($tdRegx2, $td, $tdMatch2); print_r($tdMatch2); /* Array ( [0] => <td>td1 content</td> [1] => td1 content ) */

  

?=... 正先行断言

正先行断言, 表示第一部分表达式之后必须跟着
"(T|t)he(?=sfat)" => The fat cat sat on the mat.

?!... 负先行断言

负先行断言 ?! 用于筛选所有匹配结果, 筛选条件为 其后不跟随着断言中定义的格式
"(T|t)he(?!sfat)" => The fat cat sat on the mat.

?<= ... 正后发断言
正后发断言 记作(?<=...) 用于筛选所有匹配结果, 筛选条件为 其前跟随着断言中定义的格式. 例如, 表达式 (?<=(T|t)hes)(fat|mat) 匹配 fat 和 mat, 且其前跟着 The 或 the.

"(?<=(T|t)hes)(fat|mat)" => The fat cat sat on the mat

?<!... 负后发断言
负后发断言 记作 (?<!...) 用于筛选所有匹配结果, 筛选条件为 其前不跟随着断言中定义的格式. 例如, 表达式 (?<!(T|t)hes)(cat) 匹配 cat, 且其前不跟着 The 或 the.
"(?<!(T|t)hes)(cat)" => The cat sat on cat.


常用的正则表达式

1、匹配中文

$preg = '/[x{4e00}-x{9fa5}]/u';
原文地址:https://www.cnblogs.com/hanpengyu/p/11355515.html