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.
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
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With