How can I use php and regex to strip all non-alphabetic
, spaces
and all numeric
from a string?
I've tried this:
$input = "Hello - World 12";
$output = preg_replace("/[^a-zA-Z0-9\s]/", "", $input);
Wanted output: HelloWorld
You could simply use,
$output = preg_replace("~[\W0-9_]~", "", $input);
Use this expression:
$answer = preg_replace("/[^A-Za-z]/", '', $input);
This will remove any character which are not from:
A-Z
a-z
To remove any of white spaces:
$string = preg_replace('/\s+/', '', $answer);
Remove the 0-9 and \s from your regex like so:
$input = "Hello - World 12";
$output = preg_replace("/[^a-zA-Z]/", "", $input);
Now you are checking for every character which is not (^
) lowercase a-z or uppercase a-z. Than you are replacing that character with nothing ""
.