W3docs

Remove control characters from PHP string

In PHP, you can use the preg_replace function to remove control characters from a 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:

Example of removing control characters from a string with preg_replace() function in PHP

php— editable, runs on the server

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

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

Example of removing specific control characters from a string with str_replace() function in PHP

php— editable, runs on the server

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