PHP str_替换

PHP str_替换,php,mysql,substr,Php,Mysql,Substr,我目前正在使用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”后面没有尾随的“逗号” 有没有更好

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

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

谢谢。

尝试使用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='/'$乌斯里德/我

Update2:已更改
$pattern='/'$乌斯里德/i
$pattern='/\b'$乌斯里德。”\b、 ?/i'
要解决onnodb的评论…

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

如果你想要一个这样的分隔字符串,我会在搜索和列表的两端加一个逗号,虽然如果它太长的话效率会很低

例如:

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

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

$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]);
    }
}

即,排除为空的
$值。使用“
trim
”以便
$string=“22,23,24,25”也可以处理,顺便说一句。

一个类似于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(如果存在),取消设置,然后再次内爆数组。

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


我的方法很简单:在列表中添加逗号,用一个逗号替换“、23”,然后删除多余的逗号。快速简单

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

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

这正是我所想的,非常有用+Daryl也是1,我可能会用它来做其他事情。再次感谢。该模式将把$usrID=23的“14150233”改为“14150”——这是不正确的。
$usrID = 23;
$string = "22,23,24,25";
$receivers = trim(str_replace(",$usrID,", ',', ",$string,"), ',');