nn2 nn2 - 1 year ago 205
PHP Question

PHP strip punctuation

Let's say I have this:

$hello = "Hello, is StackOverflow a helpful website!? Yes!";

and I want to strip punctuation so it outputs as:


How can I do that?

Answer Source
# 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



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download