2013-10-20 19 views
0

我有這樣的事情:怎樣的preg_replace或str_replace函數 '] [' 或 '] [' 與 'BR'

[shortcode] text [/shortcode] [shortcode_2] text [/shortcode_2][button] [shortcode_3] text [/shortcode_3] [image] text 

怎樣的preg_replace(或str_replace函數),所以<br />被插入到每個 ']['之間或'] ['

編輯:

爲了讓事情儘可能明確...

輸入:

[shortcode] text [/shortcode] [shortcode_2] text [/shortcode_2][button] [shortcode_3] text [/shortcode_3] [image] text 

輸出:

[shortcode]<br />text<br />[/shortcode]<br />[shortcode_2]<br />text<br />[/shortcode_2]<br />[button]<br />[shortcode_3]<br />text<br />[/shortcode_3]<br />[image]<br />text 

回答

1

使用preg_replace_callback

$r = preg_replace_callback('/\]([^\]]+)?(\[)|([^\]]+$)/', function($matches) { 

    var_dump($matches); 

    if (!strlen($matches[1])) { 
     return ""; 
    } else if (!isset($matches[1]) || !strlen(trim($matches[1]))) { 
     return "]<br />["; 
    } else { 
     return "]<br />" . trim($matches[1]) . "<br />["; 
    } 

}, '[shortcode] text [/shortcode] [shortcode_2] text [/shortcode_2][button] [shortcode_3] text [/shortcode_3] [image] text'); 
+0

謝謝!難道你很難解釋一點,我對正則表達式沒有經驗。是的,它似乎沒有工作。 – Dameer

+0

那麼,我測試您的輸入,並正常工作:https://eval.in/56141。正如你可以在''[']之間插入'
'。正則表達式簡單地匹配']' - '空格或空格' - ''' – pNre

+0

是的,它工作正常,但只是部分。我的不好,我意識到我不夠清楚,我已經更新了我的問題,希望它現在有意義。謝謝你的努力! – Dameer