21,893
社区成员




$str = 'abcd ef #[g h i ]# jkl #[ m n]#op q';
//该方法适合#[ ]#中只有一个空格的情形,如果是#[g h i]#则会被替换成#[g h i]#
echo preg_replace("/ (?!\w*\]#)/", ' ', $str);
//该方法适合所有情形
$arr = preg_split("/(#\[.*?\]#)/", $str, -1, PREG_SPLIT_DELIM_CAPTURE);
$output = '';
for ($i = 0, $j = count($arr); $i < $j; ++$i) {
if ($i % 2 == 0) $output .= str_replace(' ', ' ', $arr[$i]);
else $output .= $arr[$i];
}
echo $output;