In PHP, regular expression to remove the pound sig

2019-07-03 02:47发布

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?

标签: php regex
7条回答
老娘就宠你
2楼-- · 2019-07-03 03:29

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.

查看更多
\"骚年 ilove
3楼-- · 2019-07-03 03:32
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
}
查看更多
Viruses.
4楼-- · 2019-07-03 03:36

@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
查看更多
我只想做你的唯一
5楼-- · 2019-07-03 03:38

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);
查看更多
闹够了就滚
6楼-- · 2019-07-03 03:41

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);
查看更多
欢心
7楼-- · 2019-07-03 03:42

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.

查看更多
登录 后发表回答