Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP strip punctuation keep apostrophe

Tags:

regex

php

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?

like image 755
droughtrain Avatar asked Dec 21 '25 23:12

droughtrain


1 Answers

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.

like image 128
anubhava Avatar answered Dec 24 '25 12:12

anubhava