PHP 正则表达式函数
1. PHP 正则表达式函数简介
PHP 提供了多种允许使用正则表达式的内置函数。这些函数是处理复杂字符串搜索、替换和分割的强大工具。
以下是一些最常用的正则表达式函数:
preg_match()- 如果在字符串中找到匹配项则返回 1,否则返回 0。preg_match_all()- 返回在字符串中找到模式匹配的次数。preg_replace()- 返回一个新字符串,其中匹配的模式被另一个字符串替换。preg_split()- 使用正则表达式作为分隔符,将字符串分割为数组。preg_grep()- 返回一个仅包含输入中与给定模式匹配的元素的数组。
2. PHP preg_match() 函数
preg_match() 函数用于检查字符串是否包含特定的模式。
示例:
使用正则表达式在字符串中执行对 "w3schools" 的不区分大小写搜索:
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo preg_match($pattern, $str); // 输出 13. PHP preg_match_all() 函数
preg_match_all() 函数返回在字符串中找到某个模式的总次数。
示例:
使用正则表达式不区分大小写地计算字符串中 "ain" 出现的次数:
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str); // 输出 44. PHP preg_replace() 函数
preg_replace() 函数会将字符串中所有匹配该模式的部分替换为指定的另一个字符串。
示例:
使用不区分大小写的正则表达式将字符串中的 "Microsoft" 替换为 "W3Schools":
$str = "Visit Microsoft!";
$pattern = "/microsoft/i";
echo preg_replace($pattern, "W3Schools", $str); // 输出 "Visit W3Schools!"5. PHP preg_split() 函数
preg_split() 函数通过正则表达式定义的匹配项作为分隔符来拆分字符串。
示例:
使用 preg_split() 将字符串拆分为组成部分:
$str = "This is a text";
$pattern = "/[\s:]/";
$components = preg_split($pattern, $str);
print_r($components);6. PHP preg_grep() 函数
preg_grep() 函数返回一个数组,其中仅包含输入数组中与给定模式匹配的元素。
示例:
从数组中获取以 "p" 开头的项目:
$input = [ "Red", "Pink", "Green", "Blue", "Purple" ];
$result = preg_grep("/^p/i", $input);
print_r($result);6.1 反向过滤
该函数还拥有第三个参数 PREG_GREP_INVERT,使用它可以反转结果,返回不匹配该模式的元素。
7. 分组 (Grouping)
可以使用圆括号 ( ) 将量词应用于整个模式,也可以用于选择模式中的部分内容作为匹配项。
示例:
使用分组搜索单词 "banana",通过查找 "ba" 后跟两次 "na":
$str = "Apples and bananas.";
$pattern = "/ba(na){2}/i";
echo preg_match($pattern, $str); // 输出 1