Created
November 13, 2014 15:13
-
-
Save ipedro/feab83a0a33cb2aa550e to your computer and use it in GitHub Desktop.
Removes accents, spaces, tabs and punctionation from a given string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+(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