0

Say I'm making a simple BBCode function using regex, and I want the [color=] tag to stop parsing at the first semicolon to avoid exploits. Now I've seen this question all over stackoverflow, but it never shows how to implement it.

$regex = '/\[colour\=/[^;]*/](.*?)\[\/colour\]/is';
$replace = '<span style="color: $1">$2</span>';

Why is this giving me the error in the title? I can't figure out regex for the life of me, so I'm really stuck here.

If it helps any, here is the original regex I wanted to implement:

/[^;]*/

2 Answers2

3

Escape the slash:

$regex = '/\[colour\=\/[^;]*\/](.*?)\[\/colour\]/is';
//            here __^    __^

or use another delimiter:

$regex = '#\[colour=/[^;]*/](.*?)\[/colour\]#is';

But I guess the regex is:

$regex = '#\[colour=/[^;]*\](.*?)\[/colour\]#is';
//       backslash here __^

According to the replacement part:

$regex = '#\[colour=([^;]+)\](.*?)\[/colour\]#is';
$replace = '<span style="color: $1">$2</span>';

Edit according to comment:

$regex = '#\[colour=(.*?)\](.*?)\[/colour\]#is';
$replace = '<span style="color: $1">$2</span>';
Toto
  • 89,455
  • 62
  • 89
  • 125
  • None of them seem to work. They all just make the [colour] tag not parse (change into html tags) at all. – sezgtfsdfsd Jan 08 '15 at 14:15
  • "none seem to work" - then the regex isn't matching anything. So start debugging to find out why. – Marc B Jan 08 '15 at 14:21
  • I'm sorry but I don't know what you mean by example. The code in my OP is already what I've got. – sezgtfsdfsd Jan 08 '15 at 14:22
  • That just seemed to create this: ` [colour=red;font-size:50pt]test with semicolon` – sezgtfsdfsd Jan 08 '15 at 14:31
  • `echo parseBBCode('[colour=blue]normal test[/colour] [colour=red;font-size:50pt]test with semicolon[/colour]');` where the parseBBCode function is pretty much what I showed in the OP (but with a preg_replace return) – sezgtfsdfsd Jan 08 '15 at 14:38
  • @sezgtfsdfsd: See my edit, is that what you want? – Toto Jan 08 '15 at 15:10
  • That was where I was at the beginning. I want it to only parse up to the first semicolon, not including the semicolon itself. – sezgtfsdfsd Jan 11 '15 at 16:15
0

Try this snippet of the code:

$text = '[colour=red]Text in red[/colour]';
$regex = '/\[colour=([^;]*)\](.*?)\[\/colour\]/is';
$replace = '<span style="color: $1">$2</span>';

echo preg_replace($regex, $replace, $text);
Tomasz Racia
  • 1,786
  • 2
  • 15
  • 23