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

by giovanny.lueilwitz , in category: PHP General , a year ago

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

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , a year 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.

Related Threads:

How to remove leading white space inside xml file in php?
How to remove leading white space inside xml file in php?
How to remove or replace alphabets from specific position in regex?
How to strip invalid characters from a string in php?
How to remove space when combining variables in powershell?
How to remove the white space around a chart in chart.js?