Home >Backend Development >PHP Tutorial >Analysis of specific code examples of PHP function preg_match()_PHP tutorial
PHP function preg_match() prototype: int preg_match (string $pattern, string $content [, array $matches])
PHP function preg_match() in $content Search the string for content that matches the regular expression given by $pattern. If $matches is provided, the matching results are placed into it. $matches[0] will contain the text that matches the entire pattern, $matches[1] will contain the first captured match of the pattern element enclosed in parentheses, and so on. This function only performs one match and ultimately returns the number of matching results of 0 or 1. Listing 6.1 shows a code example for the preg_match() function.
Code 6.1 Date and time matching
<ol class="dp-xml"> <li class="alt"><span><span>//需要匹配的字符串。date函数返回当前时间 </span></span></li> <li class=""> <span>$</span><span class="attribute"><font color="#ff0000">content</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">"Current date and time is "</font></span><span>.<br>date("Y-m-d h:i a").", </span> </li> <li class=""><span>we are learning PHP together."; </span></li> <li class="alt"><span>//使用通常的方法匹配时间 </span></li> <li class=""><span>if (preg_match ("/d{4}-d{2}-d{2} d{2}<br>:d{2} [ap]m/", $content, $m)) </span></li> <li class="alt"><span>{ </span></li> <li class=""><span>echo "匹配的时间是:" .$m[0]. "n"; </span></li> <li class="alt"><span>} </span></li> <li class=""><span>//由于时间的模式明显,也可以简单的匹配 </span></li> <li class="alt"><span>if (preg_match ("/([d-]{10}) ([d:]{5} <br>[ap]m)/", $content, $m)) </span></li> <li class=""><span>{ </span></li> <li class="alt"><span>echo "当前日期是:" .$m[1]. "n"; </span></li> <li class=""><span>echo "当前时间是:" .$m[2]. "n"; </span></li> <li class="alt"><span>} </span></li> <li class=""> <span></span><span class="tag"><strong><font color="#006699">?></font></strong></span><span> </span><?php <br /> </li> </ol>
This is a simple dynamic text string matching example. Assuming that the current system time is "13:25 on August 17, 2006", the following content will be output.
The matching time is: 2006-08-17 01:25 pm
The current date is: 2006-08-17
The current time is: 01:25 pm
The above is the PHP function preg_match() I hope you can master the specific function examples.