請教一個正則替換問題

來源:互聯網
上載者:User
有這樣的字串 比如:

get_post_title

find_my_article


這樣的字串,如何用正則替換成:GetPostTitle,FindMyArticle ?

用explode,array_map(ucword),這樣的法子用過了。現在想用正則實現,奈何功力不夠啊


這個正則該如何寫法?


回複討論(解決方案)

$s = 'get_post_title';echo preg_replace('/(^|_)(\w)/e', 'strtoupper("$2")', $s);

$s = 'get_post_title';echo preg_replace('/(^|_)(\w)/e', 'strtoupper("$2")', $s);


謝謝斑竹。能說說這個正則式的分析思路嗎?

如果是這樣的字串 :a,b,c,d 變成 'a','b','c','d' 呢?正則又如何寫法?

這樣寫比較好,e 屬性已經列在廢止之列了

$s = 'a,b,c,d';echo preg_replace_callback('/(?:^|,)([a-z])/', function($r) { return "'$r[1]'";}, $s);

謝謝啦。不過我在用Javascript實現這個的時候,貌似有些不對。請點解下

"get_post_title".replace(/(^|_)(\w)/g,function($2){return $2.toUpperCase();})//返回這樣的結果:Get_Post_Title


不知道為啥

這樣寫比較好,e 屬性已經列在廢止之列了

$s = 'a,b,c,d';echo preg_replace_callback('/(?:^|,)([a-z])/', function($r) { return "'$r[1]'";}, $s);


啟動並執行結果不太對。
我自己這樣寫的:
$s = 'a,b,c,d';echo preg_replace_callback('/(\w)/', function($r) { return "'$r[1]'";}, $s);
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.