1

我目前正在使用 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”之后没有尾随“逗号”

有没有更好的方法可以从字符串中删除特定数字?

谢谢。

4

6 回答 6

2

另一个问题是,如果您有一个用户 5 并尝试删除它们,您会将 15 变成 1,将 25 变成 2,等等。所以您必须检查两边是否有逗号。

如果你想要一个这样的分隔字符串,我会在搜索和列表的两端都放一个逗号,但如果它变得很长,效率会很低。

一个例子是:

$receivers = substr(str_replace(','.$usrID.',', ',', ','.$string.','),1,-1);
于 2009-08-04T04:28:48.477 回答
2

您可以将字符串分解为数组:

$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)

也许不像正则表达式那样“简单”;但是有一天你需要对你的元素做更多的事情(或者你的元素比简单的数字更复杂的那一天),那仍然有效:-)


编辑:如果你想删除“空”值,比如有两个逗号,你只需要修改条件,有点像这样:

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

即,排除$values那些为空的。使用了“ trim”,因此$string = "22,23, ,24,25";也可以处理,顺便说一句。

于 2009-08-04T04:29:18.477 回答
2

一个类似于 Pascal 的选项,虽然我认为有点简单:

$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,如果存在,取消设置,然后再次内爆数组。

于 2009-08-04T04:33:47.877 回答
0

我会采用简单的方法:在列表周围添加逗号,用单个逗号替换“,23”,然后删除多余的逗号。快速简单。

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

话虽如此,在逗号分隔的列表中操作值通常是糟糕设计的标志。这些值应该在一个数组中。

于 2009-08-04T09:33:02.677 回答
-1

尝试使用 preg:

<?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 的评论...

于 2009-08-04T04:25:43.293 回答
-2

简单的方法(提供所有 2 位数字):

$string = str_replace($userId, ',', $string);
$string = str_replace(',,','', $string);
于 2009-08-04T07:13:42.333 回答