正则表达式的都是匹配和替换javascript
/** * int preg_match* ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] ) * $pattern 正则表达式 * $subject 要匹配的字符串 * &$matches 匹配到的字符串 * return 匹配到的个数,没有匹配到返回0 */
下面是例子php
$pattern = "/\d{2}/"; $content = "12:34:56:78:9a"; // 执行一个正则表达式匹配, 非贪婪 if (preg_match ($pattern, $content, $m)){ print_r($m); } // 执行一个全局正则表达式匹配, 贪婪 if ($c = preg_match_all($pattern, $content, $m)){ echo "match numbers is ".$c."\n"; print_r($m); }
执行结果html
$ php run.php Array ( [0] => 12 ) match numbers is 4 Array ( [0] => Array ( [0] => 12 [1] => 34 [2] => 56 [3] => 78 ) )
<?php $pattern = "/^[a-z]*$/i"; $content = ["Mechanical Engineering", "Medicine", "Social Science", "Agriculture", "Commercial Science", "Politics" ]; // 匹配全部仅由有一个单词组成的科目名 $alonewords = preg_grep($pattern, $content); foreach($alonewords as $key => $value){ echo $key.$value."\n"; } ?>
输出结果java
$ php run.php 1Medicine 3Agriculture 5Politics
/** * mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] ) * $pattern 正则表达式 * $subject 要匹配的字符串 * $replacement 用于替换的字符串或字符串数组, replacement和subject的类型相同 * return 替换的后的对象,类型和subject相同 */
例子正则表达式
<?php $content = "Name: {Name}\nEmail: {Email}\nAddress: {Address}\n"; $patterns = ["/{Name}/", "/{Email}/", "/{Address}/"]; $replace = ["Jaime", "xsu@viewtool.com", "Chongqing China"]; echo preg_replace($patterns, $replace, $content); ?>
输出结果shell
$php run.php Name: Jaime Email: xsu@viewtool.com Address: Chongqing China
这个至关于就是最简单的模板实现了数组
PHP preg:http://php.net/manual/zh/ref.pcre.php
下面有全部的函数手册
preg_match
preg_match_all
preg_grep
preg_replace
preg_replace_callback
preg_replace_callback_array
preg_filter
grep_quote
grep_split
grep_last_error函数
若是是替换的正则表达式,能够本身写
若是仅仅是判断,推荐使用is.js这个库
官方网站
这里就很少介绍了, 官网上的很是的清楚.net