dsapkqaduj6718493 2015-04-04 19:11 采纳率: 100%
浏览 250

如何从逗号分隔的字符串中删除单词

I am trying to give my user the ability to add and remove items from a list. the list is formatted like this: item1,item2,item3 each item is separated by a comma, except the last item does not end with one and the first does not start with one. So when my user wants to remove and item for example item3 I need PHP to remove it and the comma before it. If they wanted to remove item2 I need it to also remove the comma before it and the item. If the user wants to remove item1 i need to to remove the item and the comma after it.

Im not using an array because Im storing the the list in a mysql database

This is the code that I've been trying to get to work. It works for every item except for item 1, when I try to remove item1 it can't find it because it is looking for the starting comma not the trailing one.

$skills = 'item1,item2,item3,item4';
$skillToRemove = 'item1';
if(strpos($skills, $skillToRemove . ',') == 1)
    $newSkills = str_replace(',' . $skillToRemove, '', $skills);
else
    $newSkills = str_replace($skillToRemove . ',', '', $skills);
echo $newSkills;
  • 写回答

3条回答 默认 最新

  • douliu7929 2015-04-04 19:15
    关注

    Please don't use a string! Put your items into an array and if you need to print it use implode(). But just put your items into an array like this:

    <?php
    
        $skills = ["item1", "item2", "item3", "item4"];
        $skillToRemove = 'item1';
        unset($skills[array_search($skillToRemove, $skills)]);
    
    ?>
    

    And if you want to print your list just do this:

    echo implode(",", $skills);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3