0

Regexp to match everything "except these"

I am wanting to sanitize a user input string in PHP using preg_replace() and the sanitized string should only be allowed to have plus or minus characters in it. I thought this would be a rather simple thing to do with regex, but I'm struggling to find some thing that will catch all the special characters (except for - and +) \w is a word and catches all chars Aa-Zz and 0-9 i think. \W is any non-word character so that will also catch + and - chars. Is there a regex to say \w and (\W excepting + OR -) ?

1st May 2023, 12:41 AM
Nathan Stanley
Nathan Stanley - avatar
9 Antworten
+ 7
you want your sanitized string to only contain + or - ? "everything except" could be simplified to simply except. As Orin Cook said, you need to use ^ for negation. Modifying Snehil 's code, you get: $sanitized_string = preg_replace('/[^\+\-]/', '', $string); where every character in $string except '+' or '-' gets selected and replaced with '', leaving only + or -. Like Thanos snapping his fingers😁.
1st May 2023, 2:21 AM
Bob_Li
Bob_Li - avatar
+ 3
^ is the regex symbol for "not", so eg ^\w matches anything other than alphanumerics. Unfortunately, it's also the symbol for "starts with" if you put it at the beginning of your expression, so be careful with that.
1st May 2023, 1:24 AM
Orin Cook
Orin Cook - avatar
+ 2
Do you mean keep every special character except + & -? https://code.sololearn.com/w2LYKVPFUIoI/?ref=app
1st May 2023, 1:30 AM
Just Some Random Guy
Just Some Random Guy - avatar
+ 2
<?php echo " <script> alert('Bob_Li, its could be JS also😂'); </script> "; ?>
1st May 2023, 8:51 AM
Smith Welder
Smith Welder - avatar
+ 1
You don't need regex for so simple task, .. make some filter. ASCII code 43(+) 45(-).. only these symbols... if( '+' || '-') ok... Something like that...
1st May 2023, 4:59 AM
Smith Welder
Smith Welder - avatar
+ 1
Smith Welder agreed, it can be solved without regex. But.. expand("Something like that...")😁
1st May 2023, 5:53 AM
Bob_Li
Bob_Li - avatar
+ 1
Bob_Li Its got it ✅, so expand can be is over xd
1st May 2023, 6:34 AM
Smith Welder
Smith Welder - avatar
+ 1
Smith Welder Non regex solutions (sorry for the response overload, but topics like these motivate me to brush up my very dusty php..😅) foreach(str_split($string) as $c) if($c=="+"||$c=="-") echo $c; or if you must use a variable $sanitized_str =''; foreach(str_split($string) as $c) if($c=="+"||$c=="-") $sanitized_str .= $c; echo $sanitized_str; or foreach(str_split($string) as $c) if(in_array($c,array("+","-"),TRUE)) echo $c;
1st May 2023, 7:29 AM
Bob_Li
Bob_Li - avatar
+ 1
Bob_Li shake off the dust from php, get time to use that.. 😂
1st May 2023, 9:06 AM
Smith Welder
Smith Welder - avatar