Bojangles
Bojangles

Reputation: 101513

Regex replace space in string

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().

Upvotes: 1

Views: 557

Answers (2)

dynamic
dynamic

Reputation: 48131

preg_replace('/(#[0-9a-f]{6}) ([0-9a-f]{2})/i','$1$2',$yourSource);

Upvotes: 7

Seth Robertson
Seth Robertson

Reputation: 31461

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);
?>

Upvotes: 2

Related Questions