Remove Control Characters From A String In PHP

Non text control characters can cause problems in content, especially when attempting to act upon that content.

To remove these control characters from a string use the following.

$value = preg_replace('/[^\PC\s]/u', '', $value);

The "\P" means that we want to look for unicode characters, and adding the "C" means that we want to find invisible control characters and unused code points. This is equivalent to "\p{C}".

You can also use this variant.

$value = preg_replace('/[[:cntrl:]]/u', '', $value);

The "[:cntrl:]" here denotes control characters in the text, which we then remove.

Comments

Native function FILTER_VAR (exists since PHP 5.2) with the appropriate filters :

$value = filter_var($value, FILTER_UNSAFE_RAW, FILTER_FLAG_STRIP_LOW)

Constant FILTER_FLAG_STRIP_LOW : strip characters with ASCII value less than 32.

Add new comment

The content of this field is kept private and will not be shown publicly.