Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I strip commas and periods from a string?

I have string containing something like this:

"Favourite bands: coldplay, guns & roses, etc.," 

How can I remove commas and periods using preg_replace?

like image 804
Josh R Avatar asked Dec 17 '10 14:12

Josh R


People also ask

How do you remove commas from a string?

To remove all commas from a string, call the replace() method, passing it a regular expression to match all commas as the first parameter and an empty string as the second parameter. The replace method will return a new string with all of the commas removed.

How do you remove a period and comma from a string in Python?

Use Python to Remove Punctuation from a String with Translate. One of the easiest ways to remove punctuation from a string in Python is to use the str. translate() method. The translate method typically takes a translation table, which we'll do using the .

How do you remove the comma at the end of a string in Python?

We can use the str. replace() method to remove commas from a given string as follows. Output: Original String: This, is, a, string, that, has, commas, in, it.

How do I remove commas from a list in Python?

You can remove comma from string in python by using string's replace() method.


1 Answers

You could use

preg_replace('/[.,]/', '', $string); 

but using a regular expression for simple character substitution is overkill.

You'd be better off using strtr:

strtr($string, array('.' => '', ',' => '')); 

or str_replace:

str_replace(array('.', ','), '' , $string); 
like image 141
meagar Avatar answered Sep 23 '22 10:09

meagar