Rumah > Artikel > pembangunan bahagian belakang > 正则表达式的子模式详解,正则表达式详解_PHP教程
首先,我们先看一段PHP代码:
<?<span>php </span><span>$time</span> = <span>date</span> ("Y-m-d H:i:s"<span>); </span><span>$pattern</span> = "/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/i"<span>; </span><span>if</span>(<span>preg_match</span>(<span>$pattern</span>,<span>$time</span>,<span>$arr</span><span>)){ </span><span>echo</span> "<pre class="brush:php;toolbar:false">"<span>; </span><span>print_r</span>(<span>$arr</span><span>); </span><span>echo</span> ""; } ?>
显示结果:
<span>Array ( [0] => 2012-06-23 03:08:45 )</span>
有没有注意到,显示的结果只有一条数据,即符合匹配模式的时间格式,那如果只有一条记录的话,为什么还要用数组保存呢?直接使用字符串保存不是更好?
带着这个问题,我们来看下正则表达式中的子模式。
在正则表达式中,可以使用“(”和“)”将模式中的子字符串括起来,以形成一个子模式。将子模式视为一个整体时,那么它就相当于一个单个字符。
比如,我们将以上的代码稍微修改下,改成如下:
<?<span>php </span><span>$time</span> = <span>date</span> ("Y-m-d H:i:s"<span>); </span><span>$pattern</span> = "/<span>(</span>\d{4}<span><strong>)</strong></span>-<span>(</span>\d{2}<span>)</span>-<span>(</span>\d{2}<span>)</span> <span>(</span>\d{2}<span>)</span>:<span>(</span>\d{2}<span>)</span>:<span>(</span>\d{2}<span>)</span>/i"<span>; </span><span>if</span>(<span>preg_match</span>(<span>$pattern</span>,<span>$time</span>,<span>$arr</span><span>)){ </span><span>echo</span> "<pre class="brush:php;toolbar:false">"<span>; </span><span>print_r</span>(<span>$arr</span><span>); </span><span>echo</span> ""; } ?>
注意:我只修改了$pattern,在匹配模式中,使用了括号()
执行结果:
<span>Array</span><span> ( [</span>0] => 2012-06-23 03:19:23<span> [</span>1] => 2012<span> [</span>2] => 06<span> [</span>3] => 23<span> [</span>4] => 03<span> [</span>5] => 19<span> [</span>6] => 23<span> )</span>
总结:我们可以使用小括号给整个匹配模式进行分组,默认情况下,每个分组会自动拥有一个组号,规则是,从左到右,以分组的左括号为标志,第一个出现的分组为组号1,第二个为组号2,以此类推。其中,分组0对应整个正则表达式。<br />对整个正则匹配模式进行了分组以后,就可以进一步使用“向后引用”来重复搜索前面的某个分组匹配的文本。例如:\1代表分组1匹配的文本,\2代表分组2匹配的文本等等<br />我们可以进一步修改下代码,如下所示:
<?<span>php </span><span>$time</span> = <span>date</span> ("Y-m-d H:i:s"<span>); </span><span>$pattern</span> = "/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/i"<span>; </span><span>$replacement</span> = "\$time格式为:$0<BR>替换后的格式为:\\1年\\2月\\3日 \\4时\\5分\\6秒"<span>; </span><span>print</span> <span>preg_replace</span>(<span>$pattern</span>, <span>$replacement</span>, <span>$time</span><span>); </span><span>if</span>(<span>preg_match</span>(<span>$pattern</span>,<span>$time</span>,<span>$arr</span><span>)){ </span><span>echo</span> "<pre class="brush:php;toolbar:false">"<span>; </span><span>print_r</span>(<span>$arr</span><span>); </span><span>echo</span> ""; } ?>
注意:
执行结果:
<span>$time格式为</span>:2012-06-23 03:30:31<span> 替换后的格式为:2012年06月23日 03时30分31秒 </span><span>Array</span><span> ( [</span>0] => 2012-06-23 03:30:31<span> [</span>1] => 2012<span> [</span>2] => 06<span> [</span>3] => 23<span> [</span>4] => 03<span> [</span>5] => 30<span> [</span>6] => 31<span> )</span>
<br /><br />