Remove characters in a string that does not match letters, numbers, specific symbols, and Chinese characters in PHP

Viewed 48

I want to remove a character in a string if it's not:

  • Letters
  • Numbers
  • Space or Whitespace
  • Specific symbols : ( ) . - /
  • Chinese Characters

for example:

A3M \ Mfg. (&&$) *Co; 應龙龍.

becomes:

A3M Mfg. () Co 應龙龍.

I tried to do it like this:

$string = 'A3M \ Mfg. (&&$) *Co; 應龙龍.';
$string = preg_replace('/[^-A-Za-z0-9().\/ \u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/s', '', $string);

echo $string;

but the unwanted characters are still there

1 Answers

PHP supports code points notation using \x{....} instead of \u. However there is a better way to handle this using unicode character class \p{Han} to natch all Chinese characters.

Use this regex to search:

[^-\w()./\s\p{Han}]+

Replace with an empty string.

RegEx Demo

Code:

$string = 'A3M \ Mfg. (&&$) *Co; 應龙龍.';
$string = preg_replace('~[^-\w()./\s\p{Han}]+~u', '', $string);
echo $string;
//=> "A3M  Mfg. () Co 應龙龍."

Note that it might leave few instances of double spaces due to presence of spaces around removable characters in your original string.

Related