Remove All Slashes From Forms Using PHP Regular Expressions
When you submit this form the php script will remove all the backslashes and print the output below.
This is the output:
$dirtyString = '\r\n';
$badFriends = '/(\\\)/';
$noMoreSlashes=preg_replace($badFriends, '', $dirtyString);
echo $noMoreSlashes;
output: rn
Looks easy at first, but then you may ask yourself why would you need three backslashes in the expression just to find one in the string?
$noMoreSlashes = str_replace('\\','',$dirtyString);
//str_replace is likely the fastest way to remove strings and would work for many applications. However, having a regex can sometimes come in handy.
echo $noMoreSlashes;
output: rn
Here you can see we needed two backslashes to find and replace a single backslash. If we used one backslash the php parser would have escaped the second single quote leaving the first one open.
By using a second backslash we escape the first one. Similarly if we used three backslashes the first two would collapse into one and we would have one left in front of the single quote:
$noMoreSlashes = str_replace('\\\','',$dirtyString);
//the php parser reads the first two backslashes as one then thinks the next backslash is escaping the single quote.
echo $noMoreSlashes;
output: Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING
In the string $badFriends, the first two backslashes collapse down and the last one 'escapes' the parenthesis. This is ok because when using single quotes php really only cares about escaping backslashes and single quotes.
In our our regex replacer backslashes must be escaped. The first two backslashes are escaping the third one. We could also use four backslashes for the same effect. The first two collapse and the second two collapse and the regex has them escape each other.
I am not sure if my explanation is 100% accurate but I hope it is enough to help someone. Check back soon because I will post a version of this regex to help protect against email header injections.
Special thanks to skdevelopment for honing in on this issue. Understanding this function would have taken me forever without it.
quality article
It’s good to read a quality article. I enjoy plenty of the articles on your site.