一、正則表達式基礎
正則表達式是用來描述字元串模式的一種工具,其使用規則比較複雜,但是能夠對字元串進行強大的模式匹配功能。在PHP中,使用preg_match()函數可以進行正則表達式的匹配,該函數的語法如下:
preg_match($pattern, $string, $matches, $flags, $offset);
其中,$pattern表示正則表達式的模式,$string表示要匹配的字元串,$matches表示存放匹配結果的數組,$flags表示匹配標誌,$offset表示從字元串的哪個位置開始匹配。
例如,使用正則表達式判斷一個字元串是否為手機號:
$pattern = '/^1[3|4|5|7|8][0-9]{9}$/'; $string = '13900001111'; if(preg_match($pattern, $string)) { echo '是手機號'; } else { echo '不是手機號'; }
二、用正則表達式替換字元串
在PHP中,使用preg_replace()函數進行正則表達式的替換操作。該函數的語法如下:
preg_replace($pattern, $replacement, $string, $limit, &$count);
其中,$pattern、$string和$limit參數的含義同preg_match()函數,而$replacement表示要替換成的內容,$count表示替換的次數。
例如,我們可以使用正則表達式將字元串中的所有空格替換為逗號:
$pattern = '/\s+/'; $replacement = ','; $string = 'hello world'; $new_string = preg_replace($pattern, $replacement, $string); echo $new_string; // 輸出:hello,world
三、使用正則表達式進行字元串提取
正則表達式除了可以對字元串進行替換,還可以對字元串進行提取。在PHP中,可以使用preg_match_all()函數進行正則表達式的提取操作。該函數的語法如下:
preg_match_all($pattern, $string, $matches, $flags, $offset);
其中,$pattern、$flags、$offset參數的含義同preg_match()函數,$string表示要提取的字元串,$matches表示匹配到的結果數組。
例如,我們可以使用正則表達式提取HTML中所有的鏈接:
$pattern = '/([\s\S]*?)/'; $string = '百度一下,你就知道'; preg_match_all($pattern, $string, $matches); print_r($matches); // 輸出:Array ( [0] => Array ( [0] => 百度一下,你就知道 ) [1] => Array ( [0] => https://www.baidu.com ) [2] => Array ( [0] => 百度一下,你就知道 ) )
四、使用正則表達式進行多重匹配
在PHP中,除了使用preg_match_all()函數之外,還可以使用preg_replace_callback()函數進行多重匹配。該函數的語法如下:
preg_replace_callback($pattern, $callback, $subject, $limit, &$count);
其中,$pattern和$limit參數的含義同preg_replace()函數,$subject表示要進行匹配的字元串,$callback表示用來替換匹配到的結果的回調函數。
例如,我們可以使用正則表達式匹配字元串中的所有單詞,並將其替換成對應的數字:
$words = array('hello', 'world', 'php'); $string = 'hello world, this is php'; $reg = '/\b(' . implode('|', $words) . ')\b/'; $callback = function($matches) use ($words) { return array_search($matches[1], $words) + 1; }; $new_string = preg_replace_callback($reg, $callback, $string); echo $new_string; // 輸出:1 2, this is 3
五、正則表達式的特殊字元
在正則表達式中,有些字元具有特殊含義,需要注意。下面列舉一些常見的特殊字元:
.
匹配任意字元,除了換行符^
匹配輸入字元串的開始位置$
匹配輸入字元串的結束位置*
匹配前面的子表達式零次或多次+
匹配前面的子表達式一次或多次?
匹配前面的子表達式零次或一次{n}
匹配前面的子表達式恰好n次{n,}
匹配前面的子表達式至少n次{n,m}
匹配前面的子表達式至少n次,至多m次|
分隔兩個規則,匹配其中一個[]
匹配方括弧中的任意一個字元[^]
匹配除了方括弧中的任意一個字元以外的字元\
轉義字元,用來匹配特殊字元本身
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/197177.html