Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove comma white space during explode and replace?

$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?

like image 980
limo Avatar asked Feb 14 '11 00:02

limo


4 Answers

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.

like image 157
RobertPitt Avatar answered Oct 28 '22 05:10

RobertPitt


$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

like image 37
Jonah Avatar answered Oct 28 '22 04:10

Jonah


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?

like image 37
Colin O'Dell Avatar answered Oct 28 '22 04:10

Colin O'Dell


There are many ways to do this but perhaps the simplest is just:

$data = str_replace(',,', ',', $data);
like image 37
too much php Avatar answered Oct 28 '22 04:10

too much php