How to strip invalid characters from a string in php?

Member

by brandy , in category: PHP General , 10 months ago

How to strip invalid characters from a string in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , 10 months ago

@brandy 

To strip invalid characters from a string in PHP, you can use regular expressions and the "preg_replace" function. Here's an example:

1
2
3
4
5
6
7
$string = "This is a string with invalid characters: #$^&%*";

$pattern = '/[^A-Za-z0-9 ]/'; // matches any character that is not a letter, number, or space

$strippedString = preg_replace($pattern, '', $string);

echo $strippedString; // Outputs: "This is a string with invalid characters "


In this example, the regular expression pattern "/[^A-Za-z0-9 ]/" matches any character that is not a letter (uppercase or lowercase), number, or space. The "preg_replace" function replaces all matching characters with an empty string, effectively removing them from the original string.