1

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

Daan
  • 2,680
  • 20
  • 39

4 Answers4

2

You could simply use,

$output = preg_replace("~[\W0-9_]~", "", $input);
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

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);
Pupil
  • 23,834
  • 6
  • 44
  • 66
1
$output = preg_replace('/[\W\d_]/i', '', $input);
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
0

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 "".

RichardBernards
  • 3,146
  • 1
  • 22
  • 30