regex - php preg_replace with empty string replacement character does not work on non printable characters
Get the solution ↓↓↓I'm trying to remove non printable characters in a string, except some characters that I need.
$arr = ['Ù', 'é', '€'];
$string = "é & Ù @ ♣ ☂ % & € À";
$acceptedChars = implode('\\', $arr);
$string = preg_replace('/[^[:print:] ' . $acceptedChars . ']/', '', $string);
echo 'Test : ' . $string;
My issue is that instead of replacing the unwanted characters by an empty string as set in the second parameter, I get this instead :
Answer
Solution:
To remove all chars other than printable ASCII chars and$acceptedChars
you
can use
$string = preg_replace('/[^ -~' . $acceptedChars . ']/u', '', $string);
See the PHP demo.
The -~
pattern is a known pattern to match any printable ASCII chars.
Theu
modifier is necessary to make the regex work with Unicode strings.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: undefined array key
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.