我有这样的东西:
[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
使用
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');
\K
释放它),后跟零个或多个空格(除非在字符串末尾)或preg_replace_callback()
不需要。
代码:(演示)
$string = '[shortcode] text [/shortcode] [shortcode_2] text [/shortcode_2][button] [shortcode_3] text [/shortcode_3] [image] text';
echo preg_replace('#\[[^\]]+]\K *(?!$)|(?!^)(?: +|(?<! ))(?=\[[^\]]+])#', '<br />', $string);
输出:
[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