Remove Everything Except Letters from PHP String

Replace all characters except letters, numbers, spaces and underscores

I normally use something like:

$string = preg_replace("/[^ \w]+/", "", $string);

That replaces all non-space and non-word characters with nothing.

Remove all characters except letters, '', and ''

REGEX

Use the following and replace with an empty string:

[^0-9a-z<> ]+

And use the i modifier to make it work for Uppercase as well (Case insensitive match)

DEMO

Explanation

[^0-9a-z<> ]+           any character except: '0' to '9', 'a' to'z', '<', '>', ' '
(1 or more times(matching the most amount possible))

PHP

$re = "/[^0-9a-z<> ]+/i"; 
$str = "5 < 3 is @true";
$subst = "";

$result = preg_replace($re, $subst, $str);

PHP - remove all non-numeric characters from a string

You can use preg_replace in this case;

$res = preg_replace("/[^0-9]/", "", "Every 6 Months" );

$res return 6 in this case.

If want also to include decimal separator or thousand separator check this example:

$res = preg_replace("/[^0-9.]/", "", "$ 123.099");

$res returns "123.099" in this case

Include period as decimal separator or thousand separator: "/[^0-9.]/"

Include coma as decimal separator or thousand separator: "/[^0-9,]/"

Include period and coma as decimal separator and thousand separator: "/[^0-9,.]/"

PHP regex to strip all characters except letters, numbers, commas, hyphens and underscores

Just put - at the start or at the end because hyphen inside a char class has special meaning. and also don't forget to put comma inside the negated character class .

$clean_input = preg_replace("/[^-\w,]/", "", $input);

PHP Remove all non letters

you can use preg_replace() function to replace the part of string using regex

to keep only letters you can use as follow it will also remove space( add \s from expression to keep space)

preg_replace('/[^a-zA-Z]/','',$string);

to keep space in the string or any character to keep you can add it in []

 preg_replace('/[^a-zA-Z\s]/','',$string);

preg_replace to remove all characters except dashes, letters, numbers, spaces, and underscores

You could do something like below:

    $string = ';")<br>kk23how nowbrowncow_-asdjhajsdhasdk32423ASDASD*%$@#!^ASDASDSA4sadfasd_-?!'; 
$new_string = preg_replace('/[^ \w-]/', '', $string);
echo $new_string;
  • [^] represents a list of characters NOT to match
  • \w is a short for word character [A-Za-z0-9_]
  • - matches a hyphen literally

Remove all non-numeric characters from a string; [^0-9] doesn't match as expected

Try this:

preg_replace('/[^0-9]/', '', '604-619-5135');

preg_replace uses PCREs which generally start and end with a /.



Related Topics



Leave a reply



Submit