In PHP, I want to remove the pound sign (#) from a hex string if it exists.
I tried the following:
$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
How can I remove the pound only if it exists?
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.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
:@ennuikiller is correct, no escaping necessary. Also, you don't need to check for a match, just replace it:
OUTPUT
If you're just looking for a pound sign at the beginning of a string, why not use something simpler than regular expressions?
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:However, notice that the call to
preg_match
is completely redundant. You are already checking if it exists inpreg_replace
! :) Therefore, just do this:You have to assign the response back to the variable:
Also, you don't need to do the check with preg_match at all, it's redundant.