Question

I'm writing some PHP to convert BBcode to HTML.

I would like to convert this BBcode:

[quote]
Hello World
[/quote]

to the following:

<blockquote>Hello World</blockquote>

The preg_replace function that I'm using to perform this is:

preg_replace("/\[quote\](.+?)\[\/quote\]/s", "<blockquote>\\1</blockquote>", $bbCode);

This almost does everything I need it to, but my problem is that it carries through the \n's from before and after 'Hello World', and produces:

<blockquote>
Hello World
</blockquote>

Any ideas how I could fix this? All help very much appreciated.

Was it helpful?

Solution

Try this regular expression:

/\[quote\]\s*(.+?)\s*\[\/quote\]/s

OTHER TIPS

You need to escape backslashes inside of double-quotes. Instead of "\[", you need "\\[".

A possibility would be to use the 'e' regex-modifier, to call, for instance, the trim function on the string.

Quoting that page of the manual :

e (PREG_REPLACE_EVAL)
If this modifier is set, preg_replace() does normal substitution of backreferences in the replacement string, evaluates it as PHP code, and uses the result for replacing the search string. Single quotes, double quotes, backslashes (\) and NULL chars will be escaped by backslashes in substituted backreferences.

Only preg_replace() uses this modifier; it is ignored by other PCRE functions.


For instance, this code, only slightly different from yours :

$bbCode = <<<STR
[quote]
Hello World
[/quote]
STR;

$output = preg_replace("/\[quote\](.+?)\[\/quote\]/es", "'<blockquote>' . trim('\\1') . '</blockquote>'", $bbCode);
var_dump($output);

Would give you :

string '<blockquote>Hello World</blockquote>' (length=36)

ie, the trim function is called on what was matched -- note it will remove all white-spaces at the beginning and end of your string ; not only newlines, but also spaces and tabulations.

(For instance, you can take a look at Example #4 on the manual page of preg_replace)
(It's maybe a bit overkill in this case, should I add -- but it's nice to know anyway)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top