php (regular matching)

1. Basic content of regular expressions
Insert picture description here

Note:
1, General Atomics:

\d : 数字。  \D : 除了数字。
\w : 数字,字母,下划线。\W : 除了数字,字母,下划线。
\s  : 空白符 。 \S : 除了空白符  。

2. Metacharacters:

. :除了换行以外的所有字符
* : 匹配前面的内容出现 0 次及以上。
? : 匹配前面的内容出现 0 次或 1 次。
+ : 出现一次或多次。
^ : 必须以它开头。
$ : 必须以它结尾。
{n} : 恰巧出现 n 次。
{n,} : 大于等于 n 次。
{n,m} : 大于等于 n, 小于等于 m.
[] : 是一个集合,匹配中括号中的任意一个字符,如:[abc]即为匹配a或b或者c。
() : 后项引用 或者是当做一个整体。
[^]: 取反。
| : 或者
[-] : 代表一个范围,如[0-9],匹配即为 0123456789

3. Mode modifier

i:不区分大小写。
m:将字符串通过分隔符进行分割,将字符串中的每一行分别进行匹配。
e: 将匹配出来的内容做一些php语法上的处理。
s: 修正 "." 的换行。
U: 取消贪婪模式。
x: 忽略模式中的空白符。
A: 必须以这个模式开头。
D: 修正 "$" 对 "\n" 的忽略。
u: 做 utf-8 中文匹配的时候使用。
g:该表达式可以进行全局匹配。

Example:

现在需要正则验证一个input框,我想输入的是非整数就自动变成空值。

The regularity is as follows:

# 不加入/g,则只返回第一个匹配,无论执行多少次均是如此,如果加入g,则第一次执行也返回第一个匹配,再执行返回第二个匹配,依次类推。

#/[^0-9]/g,这个正则表达式的意思是全局匹配非数字类型和非-的字符。

/[^0-9|-]/g



匹配到该正则后,就将input的值置空即可。

2. Subsequent reference
Insert picture description here

如果想只去除掉b标签,只保留里面的字符串,这里就需要用到后项引用。怎么样后项引用呢,就是将 .* 括起来,
然后在匹配的时候,写上 \1 ,\1 代表第一个括号里面匹配到的内容,当然为了防止 \ 将 1 转义掉,所以我们使用 \\1 .

Three, greedy mode
Insert picture description here

We want to match each b tag, namely abc and bcd ,

//如果使用下面的正则来匹配的话,会匹配出<b>abc</b><b>bcd</b>.
$pattern = '/<b>.*<\/b>/';

所以此处我们要使用 .*?来取消贪婪,?代表匹配前面的内容 0 次或者 1次。

//正则表达式改为
$pattern = '/<b>.*?</b>/';

//当然取消贪婪还有一种写法:就是在后面加上一个 U ,即:
$pattern = '/<b>.*</b>/U';

但是切记不能 .*? 和 U 一起用。

Note the use of delimiters in regular matching.
Insert picture description hereInsert picture description here

Insert picture description here

**Commonly used preg functions:**

Insert picture description here
Insert picture description here

Insert picture description here
Insert picture description here

Insert picture description here
Insert picture description here
Insert picture description hereInsert picture description here

Insert picture description here
Insert picture description here
Insert picture description here

Insert picture description here

The article is borrowed from: https://www.cnblogs.com/chrdai/p/11100233.html

Guess you like

Origin blog.csdn.net/qq_46456049/article/details/108589822