how to remove comma white space during explode and replace?
Asked Answered
G

6

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?

Gradate answered 14/2, 2011 at 0:0 Comment(4)
what are you actually trying to achieve. Why don't you just str_replace("facebook,") ? Is there a broader reason for the question?Loveinamist
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.Arbitrage
Please don't forget to select an answer if any of them were helpful to you :)Esemplastic
@Gradate 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.Neddie
D
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.

Distribute answered 14/2, 2011 at 0:5 Comment(4)
Check the manual, you can use str_replace() on an array, and it is much faster than doing it by hand.Vasty
Yea i just noticed my mistake before you posted.Distribute
array_search() is more efficient than a loop. See my answer.Byelaw
how is array_search more * efficient* then a foreach ?Distribute
B
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

Byelaw answered 14/2, 2011 at 0:17 Comment(1)
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. > codepad.org/5GTBp1r4Distribute
T
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?

Trapeze answered 14/2, 2011 at 0:10 Comment(3)
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.Esemplastic
It would break if one item is "barfacebookfoo".Byelaw
@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*.Esemplastic
V
1

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

$data = str_replace(',,', ',', $data);
Vasty answered 14/2, 2011 at 0:5 Comment(0)
S
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()

Socratic answered 14/2, 2011 at 0:6 Comment(21)
Rally, You chose preg_replace() over str_replace() even str_replace() can handle arrays.Distribute
@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.Byelaw
but aslong as the csv is constant there would be no need.Distribute
@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.Socratic
then would this not suffice str_replace(array("facebook,","facebook"),"",$data) ?Distribute
@RobertPitt: If it were constant, why would it be done? They could just say $final = "google,youtube,twitter,bing"; and be done with it.Socratic
@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.Socratic
Sorry about the constant I meant consistent, i.e. No spaces following the keywordsDistribute
@RobertPitt: The regex I specified assumes that anyhow at present.Socratic
@RobertPitt: there don't have to be spaces. If the set contained "foofacebookbar" and you used str_replace, the result would be "foobar"Byelaw
@Jonah: Good point, even the regexp above would do that if foobarfacebook, existed.Socratic
@Orbling: Uh-oh, "google,foofacebook,youtube,twitter,bing" breaks it.Byelaw
Thats a pretty simple fix: str_replace(array("facebook,",",facebook,",",facebook"),",",$data)Distribute
@RobertPitt: You forgot two cases, (i) just facebook present; (ii) facebook present at the front. Starting to think the explode was sensible. ;-)Socratic
@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.Distribute
@Orbling: I'm sure it's possible with regex, but I'm no pro.Byelaw
@Orbling: This works: (,facebook,)|(\Afacebook,)|(,facebook\Z)|(\Afacebook\Z)Byelaw
@Jonah: I added a better way anyhow.Socratic
@Jonah: Yes, that covers all the bases, I think it can be shorter though, changed my original regexp.Socratic
@Orbling: "google,facebookbar,youtube,twitter" breaks the regex option.Byelaw
@Jonah: Oh yeah, lol - guess the alternative, or your regexp is best.Socratic
N
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.

Neddie answered 2/4, 2017 at 15:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.