droughtrain
droughtrain

Reputation: 257

PHP strip punctuation keep apostrophe

Like PHP strip punctuation, but I want to keep the apostrophe. Example:

I'm a student, but I don't like the school. I'll quit school.

The string after strip should be:

I'm a student but I don't like the school I'll quit school

How can I do that with regular expression or other ways?

Upvotes: 3

Views: 1521

Answers (2)

John Conde
John Conde

Reputation: 219924

Here's an adaptation of the first example:

$string = preg_replace('/[^a-z0-9\' ]+/i', '', $string);

Upvotes: 2

anubhava
anubhava

Reputation: 786291

If you want to support all Unicode punctuation characters as well then use this regex:

$str = preg_replace("#((?!')\pP)+#", '', $str);

This regex is matching Unicode punctuation character class \pP and match will avoid apostrophe character using negative lookahead.

Upvotes: 4

Related Questions