问题
Let's say I have a string:
cat,mouse,dog,horse
Is there a regex or a function that will work as follows?
1)"cat" return string ->"mouse,dog,horse"
2)"mouse" return string ->"cat,dog,horse"
3)"dog" return string ->"cat,mouse,horse"
4)"horse" return string ->"cat,mouse,dog"
I need to eliminate the selected item from the string and return the remaining parts of the string.
回答1:
You mean a function that removes a certain element? Try this:
function removeFromString($str, $item) {
$parts = explode(',', $str);
while(($i = array_search($item, $parts)) !== false) {
unset($parts[$i]);
}
return implode(',', $parts);
}
Demo
回答2:
It's as simple as exploding the string (str_getcsv) and then removing the searched term. If you have an array, then array_diff makes it very simple:
return array_diff(str_getcsv($list), array($search));
回答3:
Working demo.
This converts both string inputs to arrays, using explode()
for the list. Then you just do array_diff()
to output what's in the second array but not the first. Finally we implode()
everything back into CSV format.
$input = 'cat';
$list = 'cat,mouse,dog,horse';
$array1 = Array($input);
$array2 = explode(',', $list);
$array3 = array_diff($array2, $array1);
$output = implode(',', $array3);
来源:https://stackoverflow.com/questions/8676605/remove-an-item-from-a-comma-separated-string