views:

171

answers:

7

I want to remove the pound sign (#) from a hex string if it exists.

I tried the following code...

$str = "#F16AD3";

//Match the pound sign in the beginning
if (preg_match("/^\#/", $str)) {
  //If it's there, remove it
  preg_replace('/^\#/', '', $str);
};

print $str;

..but it didn't work. It prints out "#F16AD3".

Any ideas?

+3  A: 

If you're just looking for a pound sign at the beginning of a string, why not use something simpler than regular expressions?

if ($str[0] == '#')
  $str = substr($str, 1);
casablanca
This method works perfectly
Mark
Agreed. Shouldn't that mean upvote? +1
JGB146
This is the method I'll use but the one above (Arron's) answered the question better.
Mark
A: 

You're calling two different preg functions, this might be over-optimization, but str_replace('#' , '' , $color) solves your problem faster/efficiently. I'm sure other people will answer your specific regex issue.

sjobe
+12  A: 
echo ltrim('#F16AD3', '#');

http://php.net/manual/en/function.ltrim.php

EDIT: If you are only testing for the pound sign at the beginning of the string you can can use strpos:

if(strpos('#F16AD3', '#') === 0) {
    // found it
}
karim79
I failed to even mention a better alternative, which this is. +1
sberry2A
Strange, I am trying to +1 you, and it goes to -1 when I do??? Ah, it is because some dolt down voted you.
sberry2A
Thats a very simple and effective way to do it but doesn't check if the pound sign is there or not
Mark
@Mark: It does nothing if there is no `#`, so it's fine to call it without any check.
casablanca
+5  A: 

You have to assign the response back to the variable:

$str = preg_replace('/^\#/', '', $str);

Also, you don't need to do the check with preg_match at all, it's redundant.

Aaron
Yes; this answers the regular expression problem.
Mark
+1  A: 

@ennuikiller is correct, no escaping necessary. Also, you don't need to check for a match, just replace it:

<?php
$color = "#ff0000";

$color = preg_replace("/^#/", "", $color);
echo $color;

?>

OUTPUT

ff0000
sberry2A
Right, it automatically checks.
Mark
+3  A: 

The reason you are not seeing a change is because you are discarding the result of preg_replace. You need to assign it back to the variable:

//Match the pound sign in the beginning
if (preg_match("/^#/", $str)){
    //If it's there, remove it
    $str = preg_replace('/^#/', '', $str);
};

However, notice that the call to preg_match is completely redundant. You are already checking if it exists in preg_replace! :) Therefore, just do this:

//If there is a pound sign at the beginning, remove it
$str = preg_replace('/^#/', '', $str);
Timwi
Correct, very useful
Mark
+1  A: 

Why using preg_replace for this?

echo str_replace("#","",$color);
Webarto
He may have been doing this to ensure that it was at the start of the string.
JGB146
Correct it is invalid if its at the end
Mark