1

I'm messing about with the LESS PHP parser to get it to replace 4 colour hex codes found in IE filters. What I want to do is replace stuff like this: #ff7755 33 with #ff775533 ie. remove all the spaces in it. Obviously the characters can vary as they're colour codes. I found this question which is very close to what I want.

Right now, I have this regex which finds the string just fine:

(#([0-9a-f]){6}\s[0-9a-f]{2})

All I need now is the regex to put in the replace argument of preg_replace().

3
  • can you just do a regular string replace after you have found the string? Commented Jun 14, 2011 at 20:20
  • I could, but I don't know how to do it, as the entire string needs to be passed back to a return, not just the found/replaced bit. Or did I misunderstand you here? Commented Jun 14, 2011 at 20:21
  • Might as well just $str = preg_replace("/ /", "", $str); if you already know it's definitely a valid color code. Commented Jun 14, 2011 at 20:25

2 Answers 2

7
preg_replace('/(#[0-9a-f]{6}) ([0-9a-f]{2})/i','$1$2',$yourSource);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much yes123! I've been struggling with this for hours - I just can't get my head around regex yet. Damn head.
2

The first example in the PHP manual would seem to be exactly what you are trying to do:

<?php
$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $string);
?>

Of course for you it is:

<?php
$string = '#ff7755 33';
$pattern = '/(#[0-9a-f]{6})\s([0-9a-f]{2})/i';
$replacement = '${1}$2';
echo preg_replace($pattern, $replacement, $string);
?>

4 Comments

No need to write ${1} instead of $1. Apart from that +1.
@nikic: It was copy-paste from the PHP manual. The manual needed it because it was putting the 1 in there and since it does no harm I left it alone.
You are right, you can use it. I just don't like it if people add additional parentheses (or braces here). I mean, you could as well write ${'var'} instead of $var and occasionally you will indeed do so, but normally I would consider ${'var'} (or ${1}) bad style :)
I should have read harder. I missed this I think because I have no clue about regex. I'll get there one day!

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.