我有一个从html代码
解码的属性字符串NSAttributedString *htmlstring =[[NSAttributedString alloc] initWithData:[formatString dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}documentAttributes:nil error:&error];
在字符串中我有多个img标签,如
...
<p style="text-align: left;">
<img src="http://139.196.32.98/ueditor/php/upload/image/20160408/1460107835846711.jpg" alt="1460107835846711.jpg" width="75" height="103" style="width: 75px; height: 103px;"/>
<img src="http://139.196.32.98/ueditor/php/upload/image/20160408/1460106959338375.jpg" alt="1460106959338375.jpg" width="359" height="445" style="width: 359px; height: 445px;"/></p>
...
现在我必须调整图像大小才能修复移动屏幕。 我试过了
NSString* substring = @"<img";
NSRange range = [htmlstring rangeOfString:substring];
但它只返回第一个搜索结果,以及如何将整个标记转换为子字符串?
非常感谢
答案 0 :(得分:2)
为了继续搜索第一次出现,您需要调整搜索范围。在NSString上有一个方法可以让您这样做:
- [NSString rangeOfString:options:range:];
所以你需要在NSAttributedString下面使用它的纯文本表示,可以通过它的只读string
属性进行访问。
因此,我们的想法是每次找到匹配项时计算新的搜索范围:
NSString *substring = @"<img";
NSString *plainString = [htmlstring string];
NSRange searchRange = NSMakeRange(0, [plainString length]);
NSRange openingTagRange = [plainString rangeOfString:substring options:0 range:searchRange];
while ( openingTagRange.location < [plainString length] )
{
NSLog(@"found opening tag at %lu", (unsigned long)openingTagRange.location);
searchRange.location = NSMaxRange(openingTagRange);
searchRange.length = [plainString length] - NSMaxRange(openingTagRange);
openingTagRange = [plainString rangeOfString:openingTagString options:0 range:searchRange];
}
如果您还想将整个标记转换为子字符串,则while循环将扩展为以下内容:
while ( openingTagRange.location < [plainString length] )
{
searchRange.location = NSMaxRange(openingTagRange);
searchRange.length = [plainString length] - NSMaxRange(openingTagRange);
NSRange closingTagRange = [plainString rangeOfString:@">" options:0 range:searchRange];
if (closingTagRange.location > [plainString length])
{
break;
}
NSRange wholeTagRange = NSMakeRange(openingTagRange.location, NSMaxRange(closingTagRange) - openingTagRange.location);
NSString *wholeTagString = [plainString substringWithRange:wholeTagRange];
NSLog(@"wholeTagString == %@", wholeTagString);
searchRange.location = NSMaxRange(wholeTagRange);
searchRange.length = [plainString length] - NSMaxRange(wholeTagRange);
openingTagRange = [plainString rangeOfString:substring options:0 range:searchRange];
}
请注意,假设遇到的第一个右括号会关闭标记,我想可能并非总是这样。