str replace 删除所有逗号

str replace removing all commas

所以我这里有一个非常简单的问题。

当我 运行 在逗号分隔列表上使用 str_replace 函数删除前面带有逗号的值时,该函数会删除列表中的所有逗号。

我做错了什么?

相关对象:

$tags = "16, 17, 18, 20, 21, 22"

$tag_id = "17"

代码:

if (strpos($tags, ', '.$tag_id))
{
 //remove this in this format
  $new_tags = str_replace(', '.$tag_id, "", $tags);
}
elseif (strpos($tags, $tag_id.', '))
{
  //remove this in this format
  $new_tags = str_replace($tag_id.', ', "", $tags);
}
else
{
  //just remove the number
  $new_tags = str_replace($tag_id, "", $tags);
}

我想你真正要找的是:

$tags = (...);
$tag_id = 17;
$tags_array = explode(',', $tags);
if(($idx = array_search($tag_id , $tags_array )) !== false) {
    unset($tags_array[$idx]);
}
$tags_cleaned = implode(', ', $tags_array);
//16, 18, 20, 21, 22

Functional example

在执行 str_replace 之前,您的 $tag_id 是否已正确初始化?

我认为,在数组中处理此 csv 列表操作更容易。使用爆炸和一些数组操作可以帮助您做到这一点。

$list = array_map('trim', explode(',', $tags));
$flippedList = array_flip($list);
unset($flippedList[$tagId]);

$newTags = join(',', array_flip($flippedList));