lacrosse1991
lacrosse1991

Reputation: 3162

How can i filter a string so only alphanumeric characters are allowed through

I am currently working on a log parsing script for a server, and to prevent users from inputting malicious commands, I need to filter out all characters except for alphanumeric characters (while allowing underscores) from the inputted string, although unfortunately I do not know how to do this, so I was just wondering if someone could tell/show me what to do in order to achieve this, thanks! also as an example, say someone inputs the following: stack#@_over%flow, the program would then filter out the non-alphanumeric characters (except for underscores) in order to produce just stack_overflow, the equivalent of this in bash would be

tr -dc [:alnum:]'_'

also forgot to mention that I have tried the following, but still encounter some issues (for instance if a "!" is included in the string, i get "-bash: !": event not found"

#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char ** argv) {
    int i;
    char *p;
    if (argc > 1) {
        for (p = argv[1]; *p != '\0'; p++) {
           if (islower(*p) || isdigit(*p) || *p == '_') {
               putchar (*p);
           }
        }
        putchar ('\n');
    }
    return 0;
}

Upvotes: 0

Views: 3130

Answers (2)

zahreelay
zahreelay

Reputation: 1742

regular expressions(regex) are a great way to do this. Here is an example to show this.

Upvotes: 0

Burton Samograd
Burton Samograd

Reputation: 3638

Find the length of the string you are processing, allocate a new string of that length, iterate over every character of the input string and if it is alpha numeric (using isalnum() from ctype.h) put the character in the resulting string, else just skip it. Null terminate and copy the resulting string to the input string, free the allocated string and return the result.

Upvotes: 4

Related Questions