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
$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);
$var=preg_replace('~[^A-Za-z0-9?.!]~','',$var);
Don't forget A-Za-z
and A-z
are not same
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);
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With