php正则表达式有哪些
原创一、PHP正则表达式简介
正则表达式(Regular Expression,简称:Regex)是一种强势的文本处理工具,用于模式匹配、搜索、替换等操作。PHP中提供了多彩的正则表达式函数,令开发者可以方便地进行文本处理。本文将详细介绍PHP中的正则表达式及其相关函数。
二、PHP正则表达式函数
PHP中与正则表达式相关的函数可以分为以下几类:
1. 匹配检查函数
重点用于检查字符串是否符合某个模式。
bool preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )
bool preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] )
2. 替换函数
用于替换字符串中匹配到的部分。
mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
mixed preg_replace_callback ( array $pattern , callable $callback , mixed $subject [, int $limit = -1 [, int &$count ]] )
3. 分割函数
凭借正则表达式分割字符串。
array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )
4. 转义函数
用于转义正则表达式中的特殊字符。
string preg_quote ( string $str [, string $delimiter = NULL ] )
三、PHP正则表达式语法
PHP正则表达式遵循Perl兼容正则表达式(PCRE)的语法。以下是一些常见的正则表达式语法:
1. 字符匹配
普通字符:匹配自身
特殊字符:如. * + ?等,需要使用反斜杠\进行转义
2. 字符集
[abc]:匹配a、b或c
[^abc]:匹配除a、b、c之外的任意字符
[a-zA-Z]:匹配所有英文字母
3. 量词
?:匹配0或1次
*:匹配0或多次
+:匹配1或多次
{n}:匹配n次
{n,}:匹配至少n次
{n,m}:匹配至少n次,至多m次
4. 定位符
^:匹配字符串的起始位置
$:匹配字符串的终止位置
\b:匹配单词边界
\B:匹配非单词边界
四、示例
以下是一个明了的示例,演示怎样使用preg_match检查字符串是否符合某个模式:
$pattern = '/^https?:\/\/.+\.[a-zA-Z]{2,3}$/';
$subject = 'http://www.example.com';
if (preg_match($pattern, $subject)) {
echo '字符串符合模式';
} else {
echo '字符串不符合模式';
}
通过本文的介绍,相信您已经对PHP正则表达式有了更深入的了解。在实际开发中,灵活运用正则表达式可以大大节约代码的高效能和可读性。