PHP的preg_replace函數的問題

來源:互聯網
上載者:User
$string = "april 15, 2003";$pattern = "/(/w+) (/d+), (/d+)/i";$replacement = "/${1}1,/$3";print preg_replace($pattern, $replacement, $string);/* output   ======april1,2003*/


$replacement = "/${1}1,/$3";
"/${1}1,/$3"這個是什麼意思?


$patterns = array ("/(19|20)(/d{2})-(/d{1,2})-(/d{1,2})/",                   "/^/s*{(/w+)}/s*=/");$replace = array ("//3///4///1//2", "$//1 =");print preg_replace ($patterns, $replace, "{startdate} = 1999-5-27");


$replace = array ("//3///4///1//2", "$//1 =");這個也是什麼意思?


回複討論(解決方案)


${1} 就是匹配第一個 , $3就是匹配第三個。

${1} 就是匹配第一個 , $3就是匹配第三個。


第二段代碼是錯的,應該怎麼改才能輸出$startdate = 5/27/1999呢?

${1} 就是匹配第一個 , $3就是匹配第三個。


${1} 前面多一個轉義\斜杠不是原文輸出嗎?

第一段代碼是錯誤的,應寫作

$string = "april 15, 2003";$pattern = "/(\w+) (\d+), (\d+)/i";$replacement = "\${1}1,\$3";print preg_replace($pattern, $replacement, $string);
$string = "april 15, 2003";$pattern = "/(\w+) (\d+), (\d+)/i";$replacement = '${1}1,$3';print preg_replace($pattern, $replacement, $string);


同理第二段代碼應寫作
$patterns = array ("/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/",                   "/^\s*{(\w+)}\s*=/");$replace = array ("\\3/\\4/\\1/\\2", "$\\1 =");print preg_replace ($patterns, $replace, "{startdate} = 1999-5-27");


$n 或 \\n 均是反向參考的記號,表示第 n 個圓括弧中的內容

第一段代碼是錯誤的,應寫作

$string = "april 15, 2003";$pattern = "/(\w+) (\d+), (\d+)/i";$replacement = "\${1}1,\$3";print preg_replace($pattern, $replacement, $string);
$string = "april 15, 2003";$pattern = "/(\w+) (\d+), (\d+)/i";$replacement = '${1}1,$3';print preg_replace($pattern, $replacement, $string);


同理第二段代碼應寫作
$patterns = array ("/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/",                   "/^\s*{(\w+)}\s*=/");$replace = array ("\\3/\\4/\\1/\\2", "$\\1 =");print preg_replace ($patterns, $replace, "{startdate} = 1999-5-27");


$n 或 \\n 均是反向參考的記號,表示第 n 個圓括弧中的內容


謝謝您,${1} 前面多一個轉義斜杠\不是原文輸出的意思嗎?

雙引號中 php 會試圖將 $ 解釋為變數的前置
字串 "${1}" 將引起變數未定義的錯誤
所以要轉義掉,這樣才會把 ${1} 交給 prea_replace 去處理

雙引號中 php 會試圖將 $ 解釋為變數的前置
字串 "${1}" 將引起變數未定義的錯誤
所以要轉義掉,這樣才會把 ${1} 交給 prea_replace 去處理

謝謝您
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.