码迷,mamicode.com
首页 > 编程语言 > 详细

javascript与php字符串解析函数

时间:2018-06-08 17:29:55      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:javascript与php字符串解析函

一、javascript:
  1. 代码:
    /*
    @desc:url解析函数
    @author <lee> [<complet@163.com>]
    @param url 要查询的url
    @return ret 解析后的对象
    */
    function parseurl(url){
    var reg = /(?:([A-Za-z]+):)?(\/{0,3})?(?:(.*):(.*)@)?([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?/
    var res = reg.exec(url)
    var scheme = (res[1])?res[1]:‘http‘
    var user = (res[3])?res[3]:‘‘
    var pass = (res[4])?res[4]:‘‘
    var host = (res[5])?res[5]:‘‘
    var port = (res[6])?res[6]:‘‘
    var path = (res[7])?res[7]:‘‘
    var query = (res[8])?res[8]:‘‘
    var fragment = (res[9])?res[9]:‘‘
    var ret = {
        scheme:scheme,
        user:user,
        pass:pass,
        host:host,
        port:port,
        path:path,
        query:query,
        fragment:fragment
    }
    return ret
    }
  2. 测试:
    var url = "https://user:pass@www.baidu.com:80/a/b/?name=lee&sex=male#id";
    var ret = parseurl(url)
    console.log(ret)
  3. 输出:
    { scheme: ‘https‘,
    user: ‘user‘,
    pass: ‘pass‘,
    host: ‘www.baidu.com‘,
    port: ‘80‘,
    path: ‘a/b/‘,
    query: ‘name=lee&sex=male‘,
    fragment: ‘id‘ }

    二、php:

  4. 代码(自带):
    parse_url()
  5. 测试:
    <?php
    $url = "http://user:pass@www.baidu.com:80/a/b?name=lee&sex=male#id";
    $ret = parse_url($url);
    var_dump($ret);
  6. 输出:
    array(8) {
    ["scheme"]=>
    string(4) "http"
    ["host"]=>
    string(13) "www.baidu.com"
    ["port"]=>
    int(80)
    ["user"]=>
    string(4) "user"
    ["pass"]=>
    string(4) "pass"
    ["path"]=>
    string(4) "/a/b"
    ["query"]=>
    string(17) "name=lee&sex=male"
    ["fragment"]=>
    string(2) "id"
    }

javascript与php字符串解析函数

标签:javascript与php字符串解析函

原文地址:http://blog.51cto.com/12173069/2126496

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!