正則表達式的都是匹配和替換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