Let's say I have this:
$hello = "Hello, is StackOverflow a helpful website!? Yes!";
and I want to strip punctuation so it outputs as:
hello_is_stackoverflow_a_helpful_website_yes
How can I do that?
The 'preg_replace' function can be used to match the characters in the string and remove the unnecessary characters.
In Python, string. punctuation will give the all sets of punctuation. Parameters : Doesn't take any parameter, since it's not a function. Returns : Return all sets of punctuation.
By using the translate() method to Remove Punctuation From a String in Python. The string translate method is the fastest way to remove punctuation from a string in python. The translate() function is available in the built-in string library.
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 . maketrans() method.
# to keep letters & numbers $s = preg_replace('/[^a-z0-9]+/i', '_', $s); # or... $s = preg_replace('/[^a-z\d]+/i', '_', $s); # to keep letters only $s = preg_replace('/[^a-z]+/i', '_', $s); # to keep letters, numbers & underscore $s = preg_replace('/[^\w]+/', '_', $s); # same as third example; suggested by @tchrist; ^\w = \W $s = preg_replace('/\W+/', '_', $s);
for string
$s = "Hello, is StackOverflow a helpful website!? Yes!";
result (for all examples) is
Hello_is_StackOverflow_a_helpful_website_Yes_
Enjoy!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With