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

RobertPitt
  • 56,863
  • 21
  • 114
  • 161
limo
  • 225
  • 5
  • 12
  • what are you actually trying to achieve. Why don't you just str_replace("facebook,") ? Is there a broader reason for the question? – Jacob Feb 14 '11 at 00:04
  • 1
    implode will reserve a "space" the generated string for every element in the array, whether it has content or is blank. To remove something from the CSV string you're generating, you have to `unset()` the array element itself (e.g. remove it from the array completely), not just set it to a blank value. – Marc B Feb 14 '11 at 00:08
  • Please don't forget to select an answer if any of them were helpful to you :) – Colin O'Dell Feb 17 '11 at 20:55
  • @limo you haven't been to SO for about 5 years, so maybe you won't return, but if you do please read my answer I think you will find it the best on the page. Please consider switching the accepted answer to my lean one-liner. – mickmackusa Apr 02 '17 at 15:13

6 Answers6

6

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.

RobertPitt
  • 56,863
  • 21
  • 114
  • 161
3
$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

Jonah
  • 9,991
  • 5
  • 45
  • 79
  • If, facebook is not within the csv, then array_search would return false, we all know that php is not that strict on falsies so `false` would be interpreted as `0` thus removing the first element of `$exp`. > http://codepad.org/5GTBp1r4 – RobertPitt Feb 14 '11 at 00:45
2

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?

Colin O'Dell
  • 8,386
  • 8
  • 38
  • 75
  • Line 1 removes "facebook", so the array looks like ""google,facebook,youtube,twitter,bing". The next line converts it into an array, removing empty values (the blank space where facebook once was). Then the implode puts it back together again. Not as simple as a regex find/replace, but does use your existing code structure. – Colin O'Dell Feb 14 '11 at 00:13
  • It would break if one item is `"barfacebookfoo"`. – Jonah Feb 14 '11 at 00:21
  • @Jonah, if limo needs to match `"barfacebookfoo"`, they can easily change line 1 to use a `preg_replace()` with a pattern like `\w*facebook\w*`. – Colin O'Dell Feb 14 '11 at 14:22
1

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

$data = str_replace(',,', ',', $data);
too much php
  • 88,666
  • 34
  • 128
  • 138
0

RobertPitt's answer is the only one that bothers to loop and is more complicated than necessary. Jonah's and Colin O'Dell's methods are interesting but also heavier than necessary.

Orbling got really close with his preg_replace method, it takes too many commas away and also doesn't account for the possibility of the needle being the only value.

str_replace and preg_replace both have the clear advantage of not bothering to explode and implode. This needs to be the primary separator of the answers on this page. Methods that convert the string to an array and back to a string (not to mention additional handling) will be less efficient than the _replace methods.

I'll also note that no one mentioned array_diff in their explode/implode methods so I'll include it in my list of methods even though it relies on explode and implode. It is purely for demonstration's sake.

All str_replace methods are potentially untrustworthy if the needle is a substring of another value. Because the OP's sample input doesn't offer a conflict in this regard, I've built a str_replace method.

My one-liner preg_replace method is lean and solid.

echo preg_replace("/,facebook\b|\bfacebook,|\bfacebook\b/","",$data);

By using word boundaries (\b), my regex pattern is guarded against the possibility of a needle existing inside another value. See By checking for the needle with a leading comma, then a trailing comma, then no comma; the pattern still holds up if the only value in the string is the needle. Finally, if the needle is not present in the csv string, there is no error. THIS is the answer that SO readers should be implementing.

If you are generating the needle dynamically, you can declare your pattern two ways:

$needle="facebook";

echo preg_replace("/,$needle\b|\b$needle,|\b$needle\b/","",$data);
// OR
echo preg_replace("/,".$needle."\b|\b".$needle.",|\b".$needle."\b/","",$data);

(Demo)


My second place offering uses str_replace:

$args=[["facebook",",,"],["",","]];
echo trim(str_replace($args[0],$args[1],$data),",");

It replaces facebook then replaces any double-commas with a single comma, then trims off any leading or trailing commas from the resulting string.


And in third place, explode->array_diff->implode as a one-liner:

echo implode(',',array_diff(explode(',',$data),["facebook"]));

It's a tight one-liner, but still has to go to the trouble to explode, filter, and implode.

Here is my testing ground where I put all three methods through the paces.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
0
$data = "google,facebook,youtube,twitter,bing";

$final = preg_replace("/(^facebook,?|,facebook,|,facebook$)/", "", $data);

Alternatively:

$final = implode(',', preg_grep("/^facebook$/", explode(',', $data), PREG_GREP_INVERT));

See preg_grep()

Orbling
  • 20,413
  • 3
  • 53
  • 64
  • Rally, You chose `preg_replace()` over `str_replace()` even `str_replace()` can handle arrays. – RobertPitt Feb 14 '11 at 00:08
  • @RobertPitt: if you look, you'll see that he uses a bit of regular expression to make sure it doesn't remove a partial item. – Jonah Feb 14 '11 at 00:11
  • but aslong as the csv is constant there would be no need. – RobertPitt Feb 14 '11 at 00:13
  • @RobertPitt: a) Using it on the original string, saw no need to take it to an array just to reverse it out. b) No guarantee "facebook" will appear at the beginning or in the middle, it could be at the end, hence no comma, therefore the regex was used. The performance penalty is not that significant. – Orbling Feb 14 '11 at 00:14
  • then would this not suffice `str_replace(array("facebook,","facebook"),"",$data)` ? – RobertPitt Feb 14 '11 at 00:16
  • @RobertPitt: If it were constant, why would it be done? They could just say `$final = "google,youtube,twitter,bing";` and be done with it. – Orbling Feb 14 '11 at 00:16
  • @RobertPitt: Assuming that `str_replace()` can be guaranteed to apply the searches in the order present in the array, then yes. If it took `'facebook'` on its own first, then it would ruin it. – Orbling Feb 14 '11 at 00:17
  • Sorry about the `constant` I meant `consistent`, i.e. No spaces following the keywords – RobertPitt Feb 14 '11 at 00:18
  • @RobertPitt: The regex I specified assumes that anyhow at present. – Orbling Feb 14 '11 at 00:19
  • @RobertPitt: there don't have to be spaces. If the set contained `"foofacebookbar"` and you used str_replace, the result would be `"foobar"` – Jonah Feb 14 '11 at 00:20
  • @Jonah: Good point, even the regexp above would do that if `foobarfacebook,` existed. – Orbling Feb 14 '11 at 00:22
  • 1
    @Orbling: Uh-oh, `"google,foofacebook,youtube,twitter,bing"` breaks it. – Jonah Feb 14 '11 at 00:26
  • Thats a pretty simple fix: `str_replace(array("facebook,",",facebook,",",facebook"),",",$data)` – RobertPitt Feb 14 '11 at 00:34
  • @RobertPitt: You forgot two cases, (i) just facebook present; (ii) facebook present at the front. Starting to think the explode was sensible. ;-) – Orbling Feb 14 '11 at 00:36
  • @Orbling, i don't really care any more, if you see my post using the foreach to loop the results, that would be good enough. – RobertPitt Feb 14 '11 at 00:37
  • @Orbling: I'm sure it's possible with regex, but I'm no pro. – Jonah Feb 14 '11 at 00:38
  • 1
    @Orbling: This works: `(,facebook,)|(\Afacebook,)|(,facebook\Z)|(\Afacebook\Z)` – Jonah Feb 14 '11 at 00:41
  • @Jonah: I added a better way anyhow. – Orbling Feb 14 '11 at 00:42
  • @Jonah: Yes, that covers all the bases, I think it can be shorter though, changed my original regexp. – Orbling Feb 14 '11 at 00:43
  • @Orbling: `"google,facebookbar,youtube,twitter"` breaks the regex option. – Jonah Feb 14 '11 at 00:47
  • @Jonah: Oh yeah, lol - guess the alternative, or your regexp is best. – Orbling Feb 14 '11 at 00:52