Skip to content
Advertisement

Replace all non printable characters except newline characters

I want to replace all non printable characters, especially emojis from a text but want to retain the newline characters like n and r

I currently have this for escaping the non printable characters but it escapes n and r also:

JavaScript

Advertisement

Answer

[:print:] is a POSIX character class for printable chars. If you use it in a negated character class, you can further add characters that you do not want to match with this pattern, i.e. you can use

JavaScript

See the PHP demo:

JavaScript

The [^rn[:print:]] pattern matches all chars but printable, CR and LF chars.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement