Remove control characters from PHP string

In PHP, you can use the preg_replace function to remove control characters from a string. The regular expression /[\x00-\x1F\x7F]/ can be used to match all ASCII control characters, which can then be replaced with an empty string.

Here is an example:

<?php

$string = "Hello\r\n there!";
$clean_string = preg_replace('/[\x00-\x1F\x7F]/', '', $string);
echo $clean_string; // Outputs: "Hello there!"

In this example, the control characters \r and \n are removed from the string, resulting in "Hello world!" being printed.

Watch a course Learn object oriented PHP

You can also use the str_replace function to remove specific control characters, as shown in the example below:

<?php

$string = "Hello\r\n world!";
$clean_string = str_replace(["\r", "\n"], '', $string);
echo $clean_string; // Outputs: "Hello world!"

In this example, the control characters \r and \n are removed from the string, resulting in "Hello world!" being printed.