The ‘preg_replace’ function can be used to match the characters in the string and remove the unnecessary characters.
To keep letters and numbers −
Example
<?php
$s = "Hello, my name is Bobby !? I am 8 years !";
print_r( preg_replace('/[^a-z0-9]+/i', ' ', $s));
?>Output
This will produce the following output −
Hello my name is Bobby I am 8 years
To keep letters only −
Example
<?php
$s = "Hello, my name is Bobby !? I am 8 years !";
print_r( preg_replace('/[^a-z]+/i', ' ', $s));
?>Output
This will produce the following output −
Hello my name is Bobby I am years
To keep letters, numbers and underscore
Example
<?php
$s = "Hello, my name is Bobby !? I am 8 years !";
print_r(preg_replace('/[^w]+/', ' ', $s));
?>Output
This will produce the following output −
Hello my name is Bobby I am 8 years