在php中正則表達式用于復雜字符串的處理。所支持的正則表達式如下:
ereg()
ereg_replace()
eregi()
eregi_replace()
split()
(1)ereg,eregi
這是正規(guī)表達式匹配函數(shù),前者是大小寫有關(guān)匹配,后者則是無關(guān)的.
用法:
ereg(正規(guī)表達式,字符串,[匹配部分數(shù)組名]);
php3.0中的正規(guī)表達式大體類似于grep中用的.
(2)ereg_replace,eregi_replace
這些是替換函數(shù).
用法:
ereg_replace(正規(guī)表達式,替換串,原字符串);
字符串處理函數(shù)中有一個strtr,是"翻譯"函數(shù),類似于perl中的tr/.../.../,
用法:
strtr(字符串,"從","到");
例如:
strtr("aaabb","ab","cd")返回"cccdd".
(3)split
與explode函數(shù)有些類似,但這次可以在匹配某正規(guī)表達式的地方分割字符串.
用法:
split(正規(guī)表達式,字符串,[取出前多少項]);
這些函數(shù)都使用正則字符串做為第一個參數(shù)。php使用posix 1003.2標準所定義的擴展正則字符串。要查考posix正則表達式的完整描述請看php軟件包中regex目錄下的man頁。
example 2-4. regular expression examples
ereg("abc",$string);
/* returns true if "abc" is found anywhere in $string. */
ereg("^abc",$string);
/* returns true if "abc" is found at the beginning of $string. */
ereg("abc$",$string);
/* returns true if "abc" is found at the end of $string. */
eregi("(ozilla.[23]|msie.3)",$http_user_agent);
/* returns true if client browser is netscape 2, 3 or msie 3. */
ereg("([[:alnum:]]+) ([[:alnum:]]+) ([[:alnum:]]+)",$string,$regs);
/* places three space separated words into $regs[1], $regs[2] and $regs[3]. */
ereg_replace("^","
",$string);
/* put a
tag at the beginning of $string. */
ereg_replace("$","
",$string);
/* put a
tag at the end of $string. */
ereg_replace("/n","",$string);
/* get rid of any carriage return characters in $string. */
新聞熱點
疑難解答