gpt4 book ai didi

PHP 字符串替换

转载 作者:行者123 更新时间:2023-11-29 05:46:30 28 4
gpt4 key购买 nike

我目前正在使用 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)

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


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

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

即,排除空的 $values。 "trim"用于 $string = "22,23, ,24,25"; 也可以处理,顺便说一下。

关于PHP 字符串替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1225714/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com