繁体   English   中英

在PHP中,正则表达式从字符串中删除井号(如果存在)

[英]In PHP, regular expression to remove the pound sign from a string, if exists

在PHP中,我想从十六进制字符串中删除井号(#)( 如果存在)。

我尝试了以下方法:

$str = "#F16AD3";

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

print $str;

但它没有用。 它打印出#F16AD3

如果它存在,我怎样才能删除它?

echo ltrim('#F16AD3', '#');

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

编辑:如果您只是在字符串开头测试英镑符号,您可以使用strpos

if(strpos('#F16AD3', '#') === 0) {
    // found it
}

您必须将响应分配回变量:

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

此外,您根本不需要使用preg_match进行检查,这是多余的。

您没有看到更改的原因是您丢弃了preg_replace的结果。 您需要将其分配回变量:

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

但请注意,对preg_match的调用完全是多余的。 您已经在检查它是否存在于preg_replace :)因此,只需这样做:

//If there is a pound sign at the beginning, remove it
$str = preg_replace('/^#/', '', $str);

如果你只是在字符串的开头寻找一个英镑符号,为什么不使用比正则表达式更简单的东西呢?

if ($str[0] == '#')
  $str = substr($str, 1);

@ennuikiller是正确的,没有必要逃脱。 此外,您无需检查匹配项,只需替换它:

<?php
$color = "#ff0000";

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

?>

OUTPUT

ff0000

为什么要使用preg_replace?

echo str_replace("#","",$color);

您正在调用两个不同的preg函数,这可能是过度优化,但str_replace('#' , '' , $color)可以更快/更有效地解决您的问题。 我相信其他人会回答你的具体正则表达式问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM