preg_replace有關問題求解

來源:互聯網
上載者:User
preg_replace問題求解
我又一個字串:
$html = '
  • 《mainGood》
  • 《subGood》《subGood》
';//《mainGood》《subGood》個數不定

我現在用echo preg_replace("/(《mainGood》)|(《subGood》)/is",回呼函數,$html);

我本來想用回呼函數的方法替換《mainGood》為1,第一個《subGood》為2,第三個《subGood》為3,依次類推,我本來想在回呼函數中擷取到當前替換的是第幾個,然後確定替換內容。但是在回呼函數中不知道該怎麼寫了,請高手幫下忙。

------解決方案--------------------
是這個意思嗎?
PHP code
  • 《mainGood》《mainGood》
  • 《subGood》《subGood》《subGood》
  • ';echo preg_replace("/(《mainGood》|《subGood》)/eis","foo('$1')",$html);function foo($v){ global $count; if($v=='《mainGood》'){ return 1; }else{ $count++; return $count+1; }}//
    • 11
    • 234

    ------解決方案--------------------
    $num_mainGood = $num_subGood = 0;
    echo preg_replace_callback("/(《mainGood》)|(《subGood》)/is", '回呼函數', $html);

    function 回呼函數($r) {
    global $num_mainGood, $num_subGood;
    if($r[1]) $num_mainGood++;
    if($r[2]) $num_subGood++;
    //以下寫返回內容的代碼

    }

    ------解決方案--------------------
    PHP code
    [liangdong@bb-browser-test00.vm.baidu.com php_project]$ php main.php 
    • a
    • bc
    [liangdong@bb-browser-test00.vm.baidu.com php_project]$ cat main.php
  • 《mainGood》
  • 《subGood》《subGood》
  • EOF;$count = 0;$map = array(0 => 'a', 1 => 'b', 2 => 'c');$result = preg_replace_callback('/《mainGood》|《subGood》/i', function($match) { global $count; global $map; return $map[$count++]; }, $html);echo $result . PHP_EOL;?>
  • 聯繫我們

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