PHP Regex在BBCode标签之间获取文本

I need help with the PHP code for the following:

Get the text between each occurrence the BBCode tags [code] and [/code] in a given string so I can then replace the spaces ' ' with the nbsp character.

Long story short, I can't use CSS or DOM to do this, I need to do this on the server.

#[code](.*?)[/code]# seems to only work if there are no breaks (or newlines) between the starting and ending tags.... :(

I think you're searching for something like this

<?php
preg_match_all("/\[code\](.*?)\[\/code\]/ism", $search, $match);

hover, I'd suggest you to use BBcode parsers instead


To replace all spaces with &nbsp;, simply use preg_replace_callback

<?php
$text = preg_replace_callback("/\[code\](.*?)\[\/code\]/ism", function($match) {
     return str_replace(" ", "&nbsp;", $match[1]);
}, $search);