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:

preg_replace('/[[:^print:]]/', '', $value);

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

preg_replace('/[^rn[:print:]]/', '', $value)

See the PHP demo:

$value = "OnetlinernThe second line";
echo preg_replace('/[^rn[:print:]]/', '', $value);
// => Oneline
//    The second line

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