看板 PHP 關於我們 聯絡資訊
※ 引述《saininniang (sob)》之銘言: : 下例傳回值為 $startDate = 6/19/1969 : <?php : $patterns = array("/(19|20\d{2})-(\d{1,2})-(\d{1,2})/", "/^\s*{(\w+)}\s*=/"); : $replace = array("\\3/\\4/\\1", "$\\1 ="); : print preg_replace($patterns, $replace, "{startDate} = 1969-6-19"); : ?> : 這是我在google搜preg_replace函數的使用方法 : 但我怎麼看$patterns和$replace也沒辦法推測出像答案一樣的結果 : 我的問題應該是卡在許多符號看不懂其代表的意思 上頭的範例有些問題,我將改過的地方以黃色顯示: $patterns = array("/((19|20)\d{2})-(\d{1,2})-(\d{1,2})/", "/^\s*{(\w+)}\s*=/"); $replace = array("\\3/\\4/\\1", "$\\1="); print preg_replace($patterns, $replace, "{startDate} = 1969-6-19"); x x x / 和 / 所夾的部分代表要比對的 pattern ^ 代表從字串開頭 \s 代表 [\r\n\t\f\v] 換行、跳行、空白字串.. (感謝 alpe 補正) * 代表 0 or 1 or any \w 代表 [a-zA-Z0-9_] + 代表 1 or any \d 代表 0-9 的數字 所以 " {startDate} =" 亦符合 /^\s*{(\w+)}\s*=/ ((19|20)\d{2}) 代表會搜尋 19 或 20 開頭、並且其後接有兩位數字的 pattern 像是: 1983、2006。 \d{2}代表數字需重複兩次,換個角度來說,可看成要尋找兩位數。 \d{1,2}則是至少出現一次、至多出現兩次,如:1、31、99.. \\3/\\4/\\1 則表示將符合的模式的結果,取代為 第三個set/第四個set/第一個set \\1 表示符合 ((19|20)\d{2}) \\2 表示符合 (19|20) \\3 表示符合 (\d{1,2}) \\4 表示符合 (\d{1,2}) 就本例而言: 1969-6-19 變成 6/19/1969 by the way .. $pattern 與 $replace 為陣列時,是相對應的。 $pattern[0] 將以 $replace[0] 取代;$pattern[1] 將以 $replace[1] 取代 -- 「640K ought to be enough for anybody.!」 - Bill Gates - -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.119.199.121 剛修正了 \\2 .. 應該是 (19|20) 才對 ※ 編輯: foxzgerald 來自: 140.119.199.121 (12/15 20:52)
alpe:\s = [\r\n\t\f\v] \w=[a-zA-Z0-9_] 12/15 20:50
※ 編輯: foxzgerald 來自: 140.119.199.121 (12/15 20:57)
alpe:^ 有 開頭 及 非 兩種意義 \D = [^\d] \D = 非數字字元 12/15 20:55
foxzgerald:恩. 如果 ^ 是放在一個 set 的開頭時,如(^abc) 12/15 20:57
foxzgerald:我把修正的內容加上去了,感謝 :) 12/15 20:58
alpe:這東西落落長..還有3種表示法,php實作2種,沒記/不知道是正常 12/15 21:00
alpe:php6 以後好像只內間 preg 12/15 21:03
superGA:preg表達能力比較強 12/15 22:23
superGA:請問alpe第三種是什麼? 有資料可以看嗎? 12/15 22:24