PHP 编程/正则表达式
外观
< PHP 编程
| 字符 | 类型 | 解释 |
|---|---|---|
| . | 点 | 任何字符 |
| [...] | 方括号 | 字符类: 类中所有枚举的字符 |
| [^...] | 方括号和插入符 | 补充类: 除枚举的字符以外的所有字符 |
| ^ | 插入符 | 字符串或行开头 |
| $ | 美元符号 | 字符串或行结尾 |
| | | 管道符 | 备选 |
| (...) | 圆括号 | 捕获组: 也用于限制备选范围 |
| * | 星号 | 0、1 或多个出现 |
| + | 加号 | 1 或多个出现 |
| ? | 问号 | 0 或 1 个出现 |
| 类 | 含义 |
|---|---|
| [[:alpha:]] | 任何字母 |
| [[:digit:]] | 任何数字 |
| [[:xdigit:]] | 十六进制字符 |
| [[:alnum:]] | 任何字母或数字 |
| [[:space:]] | 任何空白字符 |
| [[:punct:]] | 任何标点符号 |
| [[:lower:]] | 任何小写字母 |
| [[:upper:]] | 任何大写字母 |
| [[:blank:]] | 空格或制表符 |
| [[:graph:]] | 可显示和可打印的字符 |
| [[:cntrl:]] | 转义字符 |
| [[:print:]] | 可打印字符,除了控制字符 |
| 表达式 | 含义 |
|---|---|
| \A | 字符串开头 |
| \b | 单词字符的开头或结尾 |
| \d | 数字 |
| \D | 非数字 |
| \s | 空格字符 |
| \S | 非空格字符 |
| \w | 字母、数字或下划线 |
| \W | 非字母、数字或下划线字符 |
| \X | Unicode 字符 |
| \z | 字符串结尾 |
?:: 在编号时忽略捕获组。例如:((?:ignored_substring|other).)?!: 否定。例如:((?!excluded_substring).)$1: 第一个捕获组的结果。
注意: 要搜索美元符号,"\$" 不起作用,因为这是变量格式,因此必须使用单引号而不是双引号: '\$'。
在 PHP 中,正则表达式模式必须始终用分隔符包围。我们通常使用重音符 (`),但也发现 / 和 #。
此外,我们可以在这些分隔符之后添加一些选项
| i | 不区分大小写 |
| m | `.` 包含回车符 |
| x | 忽略空格 |
| o | 只处理第一个匹配 |
| u | 计算 Unicode 字符(在多字节中) |
自 PHP 5.3 起,允许在正则表达式中搜索的 ereg() 函数已被 preg_match() 替换。
preg_match[3] 函数是主要的正则表达式搜索函数[4]。它返回一个布尔值,并要求两个必填参数:正则表达式模式和要扫描的字符串。
第三个参数表示存储结果数组的变量。
最后,第四个参数接受一个 PHP 标志,允许修改函数的基本行为。
- 最小示例
<?php
$string = 'PHP regex test for the English Wikibooks.';
if (preg_match('`.*Wikibooks.*`', $string)) {
print('This texts talks about Wikibooks');
} else {
print('This texts doesn\'t talk about Wikibooks');
}
?>
- 高级示例
<?php
$string = 'PHP regex test for the English Wikibooks.';
if (preg_match('`.*Wikibooks.*`', $string), results, $flag) {
var_dump(results);
} else {
print('This texts doesn\'t talk about Wikibooks');
}
?>
标志示例:[5]
- PREG_OFFSET_CAPTURE: 显示搜索子字符串在字符串中的位置。
- PREG_GREP_INVERT: 在
preg_grep()中显示反向结果。
此函数在数组中搜索[6]。
要在一个数组中获取所有真值结果,请将 preg_match 替换为 preg_match_all[7],并将 print 替换为 print_r。
筛选文件内容的示例
$regex = "/\(([^)]*)\)/";
preg_match_all($regex, file_get_contents($filename), $matches);
print_r($matches);
preg_replace 函数接受三个参数:要替换和要替换的字符串。
<?php
// Replace spaces by underscores
$string = "PHP regex test for the English Wikibooks.";
$sortedString = preg_replace('`( )`', '_', $string);
echo $sortedString;
?>
与 preg_replace() 相同,但其结果只包含替换。
分解字符串。
- ↑ https://regexper.cn/posixbrackets.html
- ↑ https://regexper.cn/unicode.html
- ↑ https://php.ac.cn/manual/en/function.preg-match.php
- ↑ https://php.ac.cn/manual/en/ref.pcre.php
- ↑ https://php.ac.cn/manual/en/pcre.constants.php
- ↑ https://php.ac.cn/manual/fr/function.preg-grep.php
- ↑ http://www.expreg.com/pregmatchall.php