Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP strip punctuation

Tags:

regex

php

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?

like image 200
test Avatar asked Apr 16 '11 22:04

test


People also ask

How to remove punctuation from a string PHP?

The 'preg_replace' function can be used to match the characters in the string and remove the unnecessary characters.

What does string punctuation return?

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.

How do I remove all punctuation from a text file in Python?

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.

How do I remove a period in Python?

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.


1 Answers

# 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!

like image 61
Wh1T3h4Ck5 Avatar answered Sep 25 '22 23:09

Wh1T3h4Ck5