Skip to content

Instantly share code, notes, and snippets.

@ipedro
Created November 13, 2014 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ipedro/feab83a0a33cb2aa550e to your computer and use it in GitHub Desktop.
Save ipedro/feab83a0a33cb2aa550e to your computer and use it in GitHub Desktop.
Removes accents, spaces, tabs and punctionation from a given string
+(NSString*)sanitizeString:(NSString *)originalString
{
// example string
// NSString *unfilteredString = @"!@#$%^&*()_+|abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
// define the characters you want to allow
NSString *allowedChars =@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
// makes an inverted set based on your setting
NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString:allowedChars] invertedSet];
// convert all to lowercase respecting accents
NSString *sanitizedString = [originalString lowercaseStringWithLocale:nil];
// trim the string
[sanitizedString stringByTrimmingCharactersInSet:[NSCharacterSet punctuationCharacterSet]];
// remove accents
sanitizedString = [[NSString alloc] initWithData: [sanitizedString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES] encoding:NSASCIIStringEncoding];
// remove forbidden characters
sanitizedString = [[sanitizedString componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:@""];
[sanitizedString stringByReplacingOccurrencesOfString:@"[ ]+"
withString:@" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, sanitizedString.length)];
// returns result
return sanitizedString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment