我目前使用str_replace函数删除usrID和紧随其后的“逗号”:

例如:

$usrID = 23;
$string = "22,23,24,25";
$receivers = str_replace($usrID.",", '', $string);  //Would output: "22,24,25"

不过,我已经注意到,如果:

$usrID = 25; //or the Last Number in the $string

它不工作,这是因为不是“25”

后一个尾随“逗号”

是否有更好的办法可以是从字符串中除去特定数目?

感谢。

有帮助吗?

解决方案

您可能会引起爆炸串入一个数组:

$list = explode(',', $string);
var_dump($list);

这将给你:

array
  0 => string '22' (length=2)
  1 => string '23' (length=2)
  2 => string '24' (length=2)
  3 => string '25' (length=2)

然后,做任何你想要的阵列上;像删除不希望再看到的条目:

foreach ($list as $key => $value) {
    if ($value == $usrID) {
        unset($list[$key]);
    }
}
var_dump($list);

它给你:

array
  0 => string '22' (length=2)
  2 => string '24' (length=2)
  3 => string '25' (length=2)

和,最后,把碎片重新在一起:

$new_string = implode(',', $list);
var_dump($new_string);

和你得到你想要的东西:

string '22,24,25' (length=8)

也许不作为“简单”作为正则表达式;但一天你需要与你的元素(或一天,你的元素比只是普通的数字更复杂)做多,仍然会工作: - )


编辑:如果你想删除“空”的价值观,当有两个逗号一样,你只需要modifiy状况,有点像这样:

foreach ($list as $key => $value) {
    if ($value == $usrID || trim($value)==='') {
        unset($list[$key]);
    }
}

即,排除是空的$values。所述“trim”用于这样$string = "22,23, ,24,25";也加以处理,顺便说一句。

其他提示

另一个问题是,如果你有一个用户5,并试图删除它们,你会转成15 1,25进2等,所以你必须检查两侧逗号。

如果你想有一个分隔字符串这样,我把双方的搜索和列表的两端逗号,尽管这会是低效的,如果它变得很长。

一个例子是:

$receivers = substr(str_replace(','.$usrID.',', ',', ','.$string.','),1,-1);

类似于帕斯卡的一种选择,虽然我认为一个位simipler:

$usrID = 23;
$string = "22,23,24,25";
$list = explode(',', $string);
$foundKey = array_search($usrID, $list);
if ($foundKey !== false) {
    // the user id has been found, so remove it and implode the string
    unset($list[$foundKey]);
    $receivers = implode(',', $list);
} else {
    // the user id was not found, so the original string is complete
    $receivers = $string;
}

基本上,将字符串转换成一个数组,找到用户ID,如果它存在,未设置,然后再次爆阵列。

我会去的简单方法:添加逗号周围的名单,替换为“23”,与一个逗号,然后删除多余的逗号。快速和简单。

$usrID = 23;
$string = "22,23,24,25";
$receivers = trim(str_replace(",$usrID,", ',', ",$string,"), ',');

随着中说,在一个逗号分隔的列表操纵值通常签署坏设计的。这些值应该是在阵列中,而不是

尝试使用预浸料:

<?php
$string = "22,23,24,25";
$usrID = '23';
$pattern = '/\b' . $usrID . '\b,?/i';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
?>

更新:改变$pattern = '/$usrID,?/i';$pattern = '/' . $usrID . ',?/i'; UPDATE2:改变$pattern = '/' . $usrID . ',?/i$pattern = '/\b' . $usrID . '\b,?/i'解决onnodb的评论...

简单方式(提供所有2个位数编号):

$string = str_replace($userId, ',', $string);
$string = str_replace(',,','', $string);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top