Kyle Ross
Kyle Ross

Reputation: 2160

PHP Regular Expression to apply brackets markup as bold

I'm working on a project right now that is a shoutbox. Since I have disabled all HTML as people would most likely forget to close a tag ans screw up everything, I wanted to make a different form of adding some flair for people to use in their posts.

What I want to to is setup a regular expression in PHP to add tags around text. Here is an example of what I want to do...

If a person types "[Hello!] How is {everyone}?" it would display as such...
"Hello! How is everyone?"

The text in between the [ ] brackets would become bold and the text in between the { } brackets would be italics.

Does anyone know how to write a regular expression for this?
Thanks!

Upvotes: 0

Views: 330

Answers (1)

NullUserException
NullUserException

Reputation: 85478

One way to do it would be:

$str = preg_replace('~\[([^\]]*)\]~', '<b>\\1</b>', $str);
$str = preg_replace('~{([^}]*)}~', '<i>\\1</i>', $str);

As seen on codepad.

That being said, I disapprove of creating yet another mark up language. Like BBCode, it's evil.

BBCode is a markup language invented by lazy programmers who didn't want to filter HTML the proper way. As a result, we now have a loose "standard" that's hard to implement. Filter your HTML the right way:

http://htmlpurifier.org/

Upvotes: 4

Related Questions