Praveen Kumar
Praveen Kumar

Reputation: 236

Remove a specified character and one neighboring comma in string

I just want to remove character "c" from variable $a

$a = "a,b,c,d";

and the variable $a must in this format

$a = "a,b,d";

I tried array(), but it not useful for my work.

Upvotes: 0

Views: 78

Answers (4)

Desolator
Desolator

Reputation: 22779

Use str_replace.

$str = str_replace(",c", "", $a);

Upvotes: 1

Rik
Rik

Reputation: 2032

If you are going for one of the str_replace() methods don't forget to include an extra , in front of your string (and stripping it afterwards) because you would have trouble stripping of the first character (if chosen).

$str = substr(str_replace(",c", "", "," . $a), 1);

Upvotes: 0

PleaseStand
PleaseStand

Reputation: 32112

You could use str_replace, or you could break the string into parts and remove the unwanted one:

$parts = explode(',', $a);
$parts = array_diff($a, array('c'));
$a = implode(',', $a);

Upvotes: 0

Amal
Amal

Reputation: 76646

Use str_replace().

<?php
$a="a,b,c,d";
echo str_replace("c,", "", $a); //output: a,b,d
?>

Upvotes: 1

Related Questions