How to remove all non printable characters in a string?
To remove all non-printable characters in a string in PHP, you can use the preg_replace function with a regular expression pattern that matches non-printable characters.
To remove all non-printable characters in a string in PHP, you can use the preg_replace function with a regular expression pattern that matches non-printable characters.
Here's an example of how you can use preg_replace to remove all non-printable characters from a string:
How to remove all non-printable characters in a string in PHP?
<?php
$string = "This is a \r\nstring with\tnon-printable\x0Bcharacters.";
$string = preg_replace('/[\x00-\x1F\x7F]/u', '', $string);
echo $string; // Outputs: "This is a string with non-printable characters."
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Learn object oriented PHP</div>
The regular expression pattern /[\x00-\x1F\x7F]/u matches control characters (ASCII 0–31 and 127). The u modifier ensures the pattern works correctly with UTF-8 encoded strings, preventing corruption of multi-byte characters.
The preg_replace function replaces all matches with an empty string, effectively removing the non-printable characters from the string.