views:

36

answers:

3

I tried this:

echo preg_replace('/[^,,$]/', '', ',test,hi,');

But gets:

,,,
+5  A: 

Do you mean

preg_replace('/^,|,$/', '', ',test,hi,');

? Inside a character class […], a leading ^ means negation, and $ doesn't have any special meanings.

You could use the trim function instead.

trim(',test,hi,', ',');
KennyTM
You beat me by 1 sec ;)
Felix Kling
Why `[^,,$]` doesn't work?
wamp
@wamp: Because this is a character group and it says *replace everything that is not a comma or a dollar sign* (a `^` at the beginning of such a group negates the group).
Felix Kling
@wamp: Because `[^,,$]` means "any characters except `,`, `,` and `$`".
KennyTM
+4  A: 

preg_replace is a bit overkill

$string = ',,ABCD,EFG,,,,';
$newString trim($string,',');
Mark Baker
+1  A: 
trim(',test,hi,',','); // echoes test,hi
Romain Deveaud