1

I'm using this

$string = preg_replace('/[\x00-\x1F\x7F\xA0]/u', '', $string);

That regex is from this link PHP: How to remove all non printable characters in a string?

The regex is removing \n but I would like to keep it. What should I do?

I think \n is 000A, so I've tried something like this (it will make all the regex stoping working) $string = preg_replace('/[\x00-\x1F\x7F\xA0[ˆ\x0A]]/u', '', $string);

I appreciate any help.

maurymmarques
  • 329
  • 1
  • 3
  • 17

3 Answers3

1

The range \x00-\x1F contains \x0A.

You have to split this range.

$string = preg_replace('/[\x00-\x09\x0B-\x1F\x7F\xA0]/u', '', $string);
Syscall
  • 19,327
  • 10
  • 37
  • 52
1

try this

[\x00-\x1F\x7F\xA0[^\x0A^\x0d]]

Explanation:

x0A - line feed (\n)

x0d - carriage return (\r)

Example:

https://regexr.com/3k3bm

bob
  • 595
  • 2
  • 18
1

Minimal change to the original regex:

/(?!\n|\r)[\x00-\x1F\x7F-\xFF]/u

Uses a negative lookahead to not match line feeds and carriage returns.

KyleFairns
  • 2,947
  • 1
  • 15
  • 35