所以我在这里有一个非常简单的问题。
当我在逗号分隔列表上运行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);
}
答案 0 :(得分: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
答案 1 :(得分:0)
在执行str_replace之前,您的$ tag_id是否已正确初始化?
答案 2 :(得分:0)
我认为,在数组中处理这个csv列表操作会更容易。使用explode和一些数组操作可以帮助你做到这一点。
$list = array_map('trim', explode(',', $tags));
$flippedList = array_flip($list);
unset($flippedList[$tagId]);
$newTags = join(',', array_flip($flippedList));