How to remove all characters except alphabets and space in php?

by giovanny.lueilwitz , in category: PHP General , 4 months ago

How to remove all characters except alphabets and space in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 4 months ago

@giovanny.lueilwitz 

You can use regular expressions and the preg_replace() function in PHP to remove all characters except alphabets and spaces. Here's an example:

1
2
3
4
5
$string = "Hello, 123 World!";

$filteredString = preg_replace("/[^a-zA-Z ]/", "", $string);

echo $filteredString;


In this example, the regular expression /[^a-zA-Z ]/ matches any character that is not an alphabet or a space. The preg_replace() function replaces all occurrences of this pattern with an empty string, effectively removing them from the original string.


The output of the code above will be: "Hello World" as all the non-alphabet characters and numbers have been removed, and only alphabets and spaces remain.