如何preg_replace或str_replace'] ['或'] ['与'BR'

时间:2013-10-20 10:23:26

标签: preg-replace str-replace

我有这样的事情:

[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 个答案:

答案 0 :(得分: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');