0

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

当我在逗号分隔的列表上运行 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);
}
4

3 回答 3

3

我认为您真正要寻找的是:

$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

功能示例

于 2015-07-09T05:16:52.267 回答
0

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

于 2015-07-09T05:17:23.697 回答
0

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

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

$newTags = join(',', array_flip($flippedList));
于 2015-07-09T05:17:51.123 回答