And here is an objective-c version:
NSString *regexToReplaceRawLinks = @"(\\b(https?):\\/\\/[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[-A-Z0-9+&@#\\/%=~_|])";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexToReplaceRawLinks
options:NSRegularExpressionCaseInsensitive
error:&error];
NSString *string = @"Sync your files to your Google Docs with a folder on your desktop. Like Dropbox. Good choice, Google storage is cheap. http://ow.ly/4OaOo";
NSString *modifiedString = [regex stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
withTemplate:@"<a href=\"$1\">$1</a>"];
NSLog(@"%@", modifiedString);
I did something like this before, but I used javascript to do it. When the view has loaded, use the delegate method webViewDidFinishLoad
, and inject javascript:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *jsReplaceLinkCode =
@"document.body.innerHTML = "
@"document.body.innerHTML.replace("
@"/(\\b(https?):\\/\\/[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[-A-Z0-9+&@#\\/%=~_|])/ig, "
@"\"<a href='$1'>$1</a>\""
@");";
[webVew stringByEvaluatingJavaScriptFromString:jsReplaceLinkCode];
}
Here's the javascript call in a non objective-c nsstring quotes version:
document.body.innerHTML = document.body.innerHTML.replace(
/(\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,
"<a href='document.location=$1'>$1</a>"
);
The regex is not perfect but will catch most of the links.
You could use stringByReplacingOccurrencesOfString:withString:
to search for your match
and replace it with the HTML link.
NSString *htmlTweet = [tweet stringByReplacingOccurrencesOfString:match withString:html];
(You might also use the range that you get from rangeOfFirstMatchInString:options:range
in stringByReplacingCharactersInRange:withString:
but I'm not sure what happens you pass a string thats longer than the ranges length in this case).
Note that your search will only find the first link in a tweet, and if there are several matches you'll miss those.