2

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.... :(

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

5 Comments

This is too greedy. Needs to use (.*?) so that you get each instance of the code block.
This worked! However, how do I replace the spaces ' ' in everything it matched with &nbsp and return the whole modified string at the end? Thanks!
@Martin. How do I change this so that I can replace the spaces with &nbsp. Your pattern gives me an array of strings that contain the text between the code tags, but how do I then replace the spaces there and then return ALL of the original string with the now modified spaces?
Nevermind, I got it through a series of str_replace calls. Crappy programming that I'm not really proud of, but it'll work. Thanks for your help @Martin and jasonbar.
@Max sorry I haven't answered your question about spaces, I had some bad day and forgot how I've done it before. Callback! Here it is, I've edited my answer, so you can use less crappy code :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.