0

I have some problems to do a regex....

I would like to replace wrong bbcode color by a default bbcode.

[color=#123456]  => OK
[color=#]        => KO
[color=]         => KO
[color=#1234567] => KO
[color=#12345]   => KO

I started to do something but I don't understand how doing multiple tests in a regex and how match just after the = with differents mix

For exemple :

101regex

Thanks a lot for your help :)

sylvain
  • 33
  • 4

3 Answers3

1

You have to matche correct color pattern, and put default color when pattern is not matched.

$color = '[color=toto]';
$default_color = '[color=#123456]';
$correct_pattern = '/\[color=#\d{6}\]/';

if(!preg_match($correct_pattern, $color, $matches)) {
    $color = $default_color;
}

echo $color;

This code will output

[color=#123456]

If you need explanation on the regExp i can explain it on the comment

Med
  • 2,035
  • 20
  • 31
  • BTW, if you need to use Hexa colors, and not only decimal colors, you will have to replace the "\d" in the regExp by "[0-9A-F]" – Med Apr 10 '15 at 15:49
  • first thank for your rapidity, Unfortunately, I must replacing in complexe text. I can't match one per one all the bbcode code. – sylvain Apr 10 '15 at 15:56
  • So you can use only the regExp '/\[color=#\d{6}\]/' or '/\[color=#[0-9A-F]{6}\]/' depending on your need – Med Apr 10 '15 at 15:57
0

I would like to complete his pattern by including the hexa case and /i argument for the regex, making the pattern:

$pattern = "/\[color=#[0-9a-f]{6}\]/i";

edit: @sylvain: "I must replacing in complexe text. I can't match one per one all the bbcode code"

Go for preg_replace then.

Answers_Seeker
  • 468
  • 4
  • 11
  • Yeah i was wondering too, maybe "/\[color=#[0-9A-Fa-f]{6}\]/i" with Upper Case letter be good too – Med Apr 10 '15 at 15:58
  • I would like the opposite :p , I need to remplace all the wrong bbcode and not match the good one. – sylvain Apr 10 '15 at 16:11
  • Use negative look arounds then : http://stackoverflow.com/questions/2637675/how-to-negate-the-whole-regex – Answers_Seeker Apr 14 '15 at 11:38
0

Arh .. I seen the ambiguity of my question .....

I would like the wrong bbcode is match by the regex. In fact all the KO item will be replace after = by #000000

 [color=#123456]  => KO
 [color=#]        => matched
 [color=]         => matched
 [color=#1234567] => matched
 [color=#12345]   => matched
 [color=lightgray]   => matched
sylvain
  • 33
  • 4