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;