PHP正则表达式不知道怎么用?欢迎查看正则指南手册

如果你有如下问题请看本文章:

  1. 正则表达式是什么?
  2. 正则表达式怎么用?
  3. 正则表达式包含哪些内容?
  4. 正则表达式相关函数用法?
一、正则表达式是什么?

身为程序员,我们一般都需要根据某种规则来构建应用程序,正如它的别名“规则表达式”。就如名字所述,它就是用来检索、替换某些符合规则的文本。
正则表达式有两种实现方式,其中一种叫POSIX正则表达式,不过相关函数在PHP5.3.0中已经废弃。我们现在使用的是Perl正则表达式。

二、正则表达式怎么用?
<?php
// 例1:匹配字符串以p开头的5位字符串
preg_match("/^p.{4}$/", 'pap22');
// 例2:匹配美元
preg_match("/([\$])([0-9])/", '$200');
// 例3:匹配linux不区分大小写
preg_match("/\blinux\b/i", 'linux');
三、正则表达式包含哪些内容?

1)虽然POSIX相关函数已经废弃,但是以下语法你一定很眼熟:

编号语法描述
中括号
1[]可用来匹配一定范围内的字符
2[0-9]匹配任何0-9的十进制数字
3[a-z]匹配任何小写a-z的字符
4[A-Z]匹配任何大写A-Z的字符
5[a-zA-Z]匹配任何大小写a-z的字符
量词
1x+匹配至少包含1个x的字符串
2x*匹配至少包含0个或多个x的字符串
3x?匹配至少包含0个或1个x的字符串
4x{2}匹配任何包含2个连续x的字符串
5x{2,3}匹配任何包含2个或3个连续x的字符串
6x{2,}匹配至少包含2个连续x的字符串
7x$任何以x结束的字符串
8^x以x开头的字符串
9[^a-zA-Z]任何不包含大小写的字符串
10x.x匹配任何包含一个x,后面是多个任意字符,然后在是x的字符串
11^.{2}$任意开头只包含2个字符的字符串
12(.*)包围的字符串
13p(hp)*匹配任何含1个p和0个或多个hp的字符串
14([\$])(0-9)+匹配$需要用(\)转义,匹配1个$与至少1个数字
预定义字符范围(不常用了解即可)
1[:alpha:]匹配任何大小写a-z的字符,如[a-zA-Z]
2[:alnum:]匹配任何大小写a-z以及数字,如[a-zA-Z0-9]
3[:cntrl:]控制字符,如制表符、退格符、反斜线
4[:digit:]0-9数字,如[0-9]
5[:graph:]ASCII33~126范围内的可打印字符
6[:lower:]小写字母字符,如[a-z]
7[:punct:]标点符号字符,如~`!@#$-+=等
8[:upper:]大写字符,如[A-Z]
9[:space:]空白字符,包括空格、水平制表符等等
10[:xdigit:]十六进制字符,如[a-fA-F0-9]

2)Perl风格

修饰符6个
I —— 不区分大小写
G —— 完成全局搜索
M —— 将字符串视为多行,匹配字符串每行的开始于结束(即^和$)
S —— 将字符串视为一行,忽略所有换行
X —— 忽略空白与注释
U —— 第一次匹配后停止。是贪婪不再贪婪。

元字符
\A —— 只匹配字符串开头
\b —— 匹配单词边界
\B —— 匹配除单词边界之外的任意字符
\d —— 匹配0-9
\D —— 匹配非数字
\s —— 匹配空白符
\S —— 匹配非空白符
[] —— 包围一个字符类
() —— 包围一个字符分组或一个反引用
$ —— 匹配尾行
^ —— 匹配首行
. —— 任意字符,除了换行
\ —— 转义,即引出下一个元字符
\w 匹配下划线字母数字
\W 匹配字符串,忽略下划线字母数字

四、正则表达式相关函数用法?
<?php
        /**
	 * 搜索所有元素返回所有匹配的数组
	 * array_grep(string pattern, array input [, int flags])
	 */
	$foods = array("pasta", "steak", "fish", "potatoes");
	// 匹配p开头的元素
	$food = preg_grep("/^p/", $foods);
	print_r($food); // Array ( [0] => pasta [3] => potatoes )


	/**
	 * 函数根据搜索模式搜索字符串,存在返回TRUE,否则返回FALSE
	 * array_match(string pattern, string string [, array matches] [,int flags [, int offset]])
	 */
	$line = "vim is the greatest word processor ever created! Oh vim, how I love thee!";
	// 在遇到vim或Vim时确定一次匹配,不区分大小写,而不匹配simplevim、vims或evim
	if (preg_match("/\bVim\b/i", $line, $match))
	{
		print_r($match); // Array ( [0] => vim )
	}


	/**
	 * 匹配所有出现
	 * preg_match_all(string pattern, string string, array matches [, int flags] [, int offset])
	 * flags 有3个值
	 * PREG_PATTERN_ORDER,默认值,$pat_array[0]返回完全匹配的值,$pat_array[1]第一个小括号中的值,以此类推。
	 * PREG_SET_ORDER,$pat_array[0]第一个完全匹配的值与第一个小括号的值...
	 * PREG_OFFSET_CAPTURE,$pat_array[0]返回完全匹配的值与偏移值,$pat_array[1]第一个小括号中的值与偏移值
	 */
	$userinfo = "Name: <b>Zeev Suraski</b> <br> Title: <b>PHP Guru</b> <br> Age: <b>20</b>";
	preg_match_all("/<b>(.*)<\/b>/U", $userinfo, $pat_array, PREG_PATTERN_ORDER);
	print_r($pat_array); 
	/*
	PREG_PATTERN_ORDER:
	Array
	(
	    [0] => Array
	        (
	            [0] => <b>Zeev Suraski</b>
	            [1] => <b>PHP Guru</b>
	            [2] => <b>20</b>
	        ) 

	    [1] => Array
	        (
	            [0] => Zeev Suraski
	            [1] => PHP Guru
	            [2] => 20
	        )
	)
	PREG_SET_ORDER:
	Array
	(
	    [0] => Array
	        (
	            [0] => <b>Zeev Suraski</b>
	            [1] => Zeev Suraski
	        )

	    [1] => Array
	        (
	            [0] => <b>PHP Guru</b>
	            [1] => PHP Guru
	        )

	    [2] => Array
	        (
	            [0] => <b>20</b>
	            [1] => 20
	        )
	)
	PREG_OFFSET_CAPTURE:
	Array
	(
	    [0] => Array
	        (
	            [0] => Array
	                (
	                    [0] => <b>Zeev Suraski</b>
	                    [1] => 6
	                )

	            [1] => Array
	                (
	                    [0] => <b>PHP Guru</b>
	                    [1] => 38
	                )

	            [2] => Array
	                (
	                    [0] => <b>20</b>
	                    [1] => 64
	                )

	        )

	    [1] => Array
	        (
	            [0] => Array
	                (
	                    [0] => Zeev Suraski
	                    [1] => 9
	                )

	            [1] => Array
	                (
	                    [0] => PHP Guru
	                    [1] => 41
	                )

	            [2] => Array
	                (
	                    [0] => 20
	                    [1] => 67
	                )

	        )
	)
	*/
	/**
	 * 在特殊含义字符添加反斜杠,包括$^*()+={}[]|\\:<>
	 * preg_quote()
	 */
	$text = "have $500.";
	echo preg_quote($text); // have \$500\.
	
	
	/**
	 * 替换匹配的字符串
	 * preg_replace(mixed pattern, mixed replacement, mixed str [, int limit [, int count]])
	 */
	$text = "This is a link to http://www.xxx.com/.";
	// echo preg_replace("/http:\/\/(.*)\//", "<a href=\"\${0}\">\${0}</a>", $text); // This is a link to <a href="http://www.xxx.com/">http://www.xxx.com/</a>.
	// 数组
	$draft = "In 2010 the company faced plummeting revenues and scandal.";
	$keywords = ["/faced/", "/plummeting/", "/scandal/"];
	$replacement = ["celebrated", "skyrocketing", "expansion"];
	echo preg_replace($keywords, $replacement, $draft); // In 2010 the company celebrated skyrocketing revenues and expansion.

	/**
	 * 自定义替换
	 * preg_replace_callback(mixed pattern, mixed replacement, mixed str [, int limit [, int count]])
	 */
	function acronym($matches)
	{
		$acronyms = [
			'WWW' => 'World wide web',
			'IRS' => 'Internal Revenue Service',
			'PDF' => 'Portable Document Format',
		];
		
		if (isset($acronyms[$matches[1]]))
			return $matches[1] . "(" . $acronyms[$matches[1]] . ")";
		else
			return $matches[1];
	}

	$text = "The <acronym>IRS</acronym> offers tax forms in <acronym>PDF</acronym> format on the <acronym>WWW</acronym>.";

	$newtext = preg_replace_callback("/<acronym>(.*)<\/acronym>/U", 'acronym', $text);
	print_r($newtext); // The IRS(Internal Revenue Service) offers tax forms in PDF(Portable Document Format) format on the WWW(World wide web).
	
	/**
	 * 以不区分大小写的方式将字符串划分不同的元素
	 * preg_split(string pattern, string string [, int limit [, int flags]])
	 */
	$delimitedText = "Jason+++Gilmore++++++++++Columbus+++OH";
	$fields = preg_split("/\++/", $delimitedText);
	print_r($fields); // Array ( [0] => Jason [1] => Gilmore [2] => Columbus [3] => OH )


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值