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;
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);
Learn to work with arrays
$skills = 'item1,item2,item3,item4';
$skillToRemove = 'item1'
$skillArray = explode(',', $skills);
$findSkill = array_search($skillToRemove, $skillArray);
if ($findSkill !== false)
unset($skillArray[$findSkill];
$skills = implode(',', $skillArray);
You can use preg_replace to remove the selected skill and trim away any leftover comma, using this:
$newSkills = trim(
preg_replace("/((?<=^)|(?<=,))\\Q$skillToRemove\\E(,|$)/", "", $skills),
","
);
Regular expression explained:
/ Begin pattern
((?<=^)|(?<=,)) Begin match with start of string (^) or comma.
The `?<=` makes sure this is will not be replaced.
\Q Begin quote skill string. Any characters between \Q and \E
including metacharacters (e.g. '+' or '.') will be treated
as literals.
$skillToRemove Match skill to remove (will be removed)
\E End of skill string quoting
(,|$) Followed by comma or end of string (will also be removed)
/ End pattern
Example:
$skills = 'item1,item2,item3,item4';
$skillToRemove = 'item4';
$newSkills = trim(
preg_replace("/((?<=^)|(?<=,))\\Q$skillToRemove\\E(,|$)/", "", $skills),
","
);
echo "Removed item4: ", $newSkills, PHP_EOL;
Output:
Removed item4: item1,item2,item3