类似于PHP的字符串解析 [英] PHP-like string parsing

查看:91
本文介绍了类似于PHP的字符串解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写各种微型控制台,并且试图弄清楚如何从链接中提取内容.例如,在PHP中,这是一个请求变量 所以:

I'm writing a mini-console of sorts and I'm trying to figure out how to extract things from a link. For example, in PHP this is a request variable so:

http://somelink.com/somephp.php?variable1=10&variable2=20

然后PHP找出url参数并将其分配给变量.

Then PHP figures out the url parameters and assigns them to a variable.

我该如何在Swift中解析这样的内容?

因此,给定我要使用的字符串:variable1 = 10和variable2 = 20等,有没有简单的方法可以做到这一点?我尝试使用Google搜索功能,但实际上并不知道我要搜索的内容.

So, given the string I'd want to take: variable1=10 and variable2=20 etc, is there a simple way to do this? I tried googling around but didn't really know what I was searching for.

我有一种非常骇人听闻的方法,但这并不是可扩展的.

I have a really horrible hacky way of doing this but it's not really extendable.

推荐答案

您需要

为查询项添加subscript运算符可能会有所帮助:

You might find it helpful to add a subscript operator for the query items:

extension NSURLComponents {
    subscript(queryItemName: String) -> String? {
        // of course, if you do this a lot, 
        // cache it in a dictionary instead
        for item in self.queryItems ?? [] {
            if item.name == queryItemName {
                return item.value
            }
        }
        return nil
    }
}

if let components = NSURLComponents(string: urlStr) {
    components["variable1"] ?? "No value"
}

这篇关于类似于PHP的字符串解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆