Master345
Master345

Reputation: 2266

PHP filter using preg_replace to allow only alphanumerics and some punctuation

I have a little problem with preg_replace.

I need a function that removes all characters except [A-z][0-9] and .!?.

I could use preg_match, but this only verifies the string, and I want to remove the characters.

This is so I don't end up putting junk characters like <p> and ;[[;[p;[ in the description META tag.

So the function must do this:

;")<br>kk23?!brkk23?!

Any help would be appreciated :D

Upvotes: 33

Views: 75088

Answers (5)

dang
dang

Reputation: 2412

$string = ';")<br>kk23?!'; 
$new_string = preg_replace("/[^A-Za-z0-9.!?]/",'',$string);
echo $new_string;

Leaves: letters, numbers, spaces, .!?


/* 3 choices. Pick one you like! */
$str = preg_replace("/[^A-Za-z0-9.!? ]/","",$str);
$str = preg_replace("/[^A-Za-z0-9.!?\s]/","",$str);
$str = preg_replace("/[^A-Za-z0-9.!?[:space:]]/","",$str);

Upvotes: 71

Aditya P Bhatt
Aditya P Bhatt

Reputation: 22071

A quick solution will be as below also:

if (preg_match('/^[\w\.]+$/', $str)) {
    echo 'Str is valid';
} else
    echo 'Str is invalid';

// string only contain the a to z , A to Z, 0 to 9 and _ (underscore)

\w - matches [a-zA-Z0-9_]+

Hope it helps.

Upvotes: 2

user3706926
user3706926

Reputation: 181

More visit to this page. I think more people getting the same problem. The better way is to try your self and get what you need. Custom yours or copy paste this php and try it :

$sample_input = '&&*9?><<script>}cat-<html>ch(_P.,,mE.:;xc##e*p32t.ion $e){di+-($e->ge69tMesPHP _f0sage()3);}';

$output = ereg_replace("[^..........]", "", $sample_input);        

echo "validate =".$output;

modify by filling this to get what you want :

 $output = ereg_replace("[^.........]", "", $sample_input);

Example : if you want only lowercase then do like this :

$output = ereg_replace("[^a-z]", $sample_input);

lower case with white space :

 $output = ereg_replace("[^a-z ]", $sample_input);

and more....., This is a simple validation method :

$username = ereg_replace("[^A-Z0-9_]", "", $username);
$fullname = ereg_replace("[^A-Za-z0-9., ]", "", $fullname);
$city     = ereg_replace("[^A-Za-z -]", "", $city);
$phone    = ereg_replace("[^0-9 +()-]", "", $phone);
$state    = ereg_replace("[^A-Za-z -]", "", $state);
$zipcode  = ereg_replace("[^0-9]", "", $zipcode);
$country  = ereg_replace("[^A-Za-z -]", "", $country);
$gender   = ereg_replace("[^mf]", "", $gender);

Try yourself, hope will help...

Upvotes: 1

Jess
Jess

Reputation: 8700

The easiest way is to just do something similar to: Just add the characters after the !, make sure to escape them if needed.

$string = "<br>kk23?!";
$string = preg_replace('/[^A-Za-z0-9 \?!]/', '', $string);

Upvotes: 2

RiaD
RiaD

Reputation: 47619

 $var=preg_replace('~[^A-Za-z0-9?.!]~','',$var);

Don't forget A-Za-z and A-z are not same

Upvotes: 9

Related Questions