$data = "google,facebook,youtube,twitter,bing";
$exp = explode(",",$data);
$rep = str_replace("facebook",$exp);
$final = implode(",",$rep);
echo $final
output// google,,youtube,twitter,bing
How can I remove this blank space with comma?
Here's what your code should look like:
$data = "google,facebook,youtube,twitter,bing";
$exp = explode(",",$data);
foreach($exp as $key => $item)
{
if(trim($item) == "facebook")
{
unset($exp[$key]); //Remove from teh array.
}
}
$final = implode(",",$rep);
echo $final;
or as long as you have no spaces within after your comers you can simply go
$data = str_replace(",facebook,",",",$data);
To many complications using the str_replace
, just use the loopy method.
$data = "google,facebook,youtube,twitter,bing";
$exp = explode(',', $data);
$index = array_search('facebook', $exp);
if ($index !== false){
unset($exp[$index]);
}
$final = implode(',', $exp);
http://php.net/array-search
You can remove empty elements from an array using array_filter($data)
:
$data = str_replace("facebook", "", "google,facebook,youtube,twitter,bing");
$exp = array_filter(explode(",",$data));
$final = implode(",",$rep);
echo $final;
http://php.net/manual/en/function.array-filter.php
"If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed."
Is that what you're looking for?
There are many ways to do this but perhaps the simplest is just:
$data = str_replace(',,', ',', $data);
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