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 -) ?
9 Answers
+ 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đ.
+ 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.
+ 2
Do you mean keep every special character except + & -?
https://code.sololearn.com/w2LYKVPFUIoI/?ref=app
+ 2
<?php echo
" <script>
alert('Bob_Li, its could be JS alsođ');
</script> ";
?>
+ 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...
+ 1
Smith Welder
agreed, it can be solved without regex.
But..
expand("Something like that...")đ
+ 1
Bob_Li
Its got it â
, so expand can be is over xd
+ 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;
+ 1
Bob_Li
shake off the dust from php, get time to use that.. đ