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 :)

2
  • 1
    Please post your regex in the question and not in a link Commented Apr 10, 2015 at 15:45
  • Sorry, I'm new in stackoverfow. Commented Apr 10, 2015 at 15:58

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

3 Comments

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]"
first thank for your rapidity, Unfortunately, I must replacing in complexe text. I can't match one per one all the bbcode code.
So you can use only the regExp '/[color=#\d{6}]/' or '/[color=#[0-9A-F]{6}]/' depending on your need
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.

3 Comments

Yeah i was wondering too, maybe "/[color=#[0-9A-Fa-f]{6}]/i" with Upper Case letter be good too
I would like the opposite :p , I need to remplace all the wrong bbcode and not match the good one.
Use negative look arounds then : stackoverflow.com/questions/2637675/…
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

Comments

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.