PCRE兼容正則表達式函數

1、字符串的匹配與查找

(1)preg_match()

根據正則表達式的模式對指定的字符串進行搜索和匹配。

int preg_match( string pattern, string subject [, array matches [, int flags]])

//matches存儲與第一個參數中的子模式的各個部分的匹配結果。

子模式:正則表達式中的子模式是使用括號括起的模式單元,數組matches中的第一個元素matches[0]保存與正則表達式pattern匹配的整體內容,而數組matches中的其他元素則按照順序保存了與正則表達式小括號內子表達式相匹配的內容。

(2)preg_match_all()

int preg_match_all( string pattern, string subject, array matches [, int flags])

//matches存儲所有的匹配結果,並且返回整個模式匹配的次數,如果出錯則返回FALSE。

preg_match()在第一次匹配成功後就停止查找。

preg_match_all()則會一直匹配到最後纔會停止,獲取到所有相匹配的結果。

(3)preg_grep()

preg_grep()函數對數組中的元素進行匹配。

array preg_grep( string pattern, array input)

//input指定被搜索的數組。

該函數返回一個數組,其中包含了第二個參數input數組中與給定的第一個參數pattern模式相匹配的單元,preg_grep()對輸入數組input的每個元素只進行一次匹配。

2、複雜字符串的替換

(1)preg_replace()

mixed preg_replace( mixed pattern, mixed replacement, mixed subject [, int limit])
該函數在字符串subject中匹配表達式pattern,並將匹配項替換成字串replacement。如果有參數limit,則替換limit次。

(2)preg_replace_callback()

mixed preg_replace_callback( mixed pattern, callback callback, mixed subject [, int limit])

此處使用一個回調函數(callback)來代替replacement參數。

ps:在preg_replace_callback()函數的回調函數中,建議使用單引號定義字符串,這樣可以保證字符串中的特殊符號不被轉義。

3、複雜字符串的分割
根據正則表達式定義的模式完成對指定字符串的分割操作。

array preg_split( string pattern, string subject [, int limit [, int flags]])



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章