【问题标题】:parse_str doesn't work when the question mark is present?问号出现时 parse_str 不起作用?
【发布时间】:2011-01-16 20:29:14
【问题描述】:

为什么我在传递带有'form.php?'之类的字符串时会出错,例如,

parse_str('form.php?category=contacts');
echo $category;

我明白了,

Notice: Undefined variable: category in C:\wamp\www\1hundred_2011_MVC\applications\CMS\category_manage.php on line xx

但是,

parse_str('category=contacts');
echo $category;

我得到了我想要的,

contacts

我该如何解决?我必须通过 'xxx.php?category=contacts' 之类的东西来获取 'contacts' 或变量中的东西。

谢谢。

【问题讨论】:

    标签: php string variables query-string


    【解决方案1】:

    parse_str 函数只解析查询字符串,而不是整个 URL。尝试使用 parse_url 并将组件设置为 PHP_URL_QUERY 先提取查询字符串,然后再使用 parse_str

    $url_query = parse_url('form.php?category=contacts', PHP_URL_QUERY);
    parse_str($url_query, $output);
    echo $output['category'];
    

    结果:

    联系人

    See it at ideone.

    【讨论】:

    • 还可以使用第二个参数来存储查询字符串中的参数...您不想像此 PHP.net 条目 [php.net/manual/en/function.parse-str.php#96035] 中提到的那样覆盖变量。
    • @Yzmir Ramirez:我已经更新了我的答案以展示这种方法。谢谢。
    【解决方案2】:

    parse_str 只接受查询字符串:

    $q = 'foo?hello=world';
    parse_str($q);
    echo ${'foo?hello'}; // outputs 'world'
    

    先去掉 URL 的开头:

    $q = 'foo?hello=world';
    parse_str(substr($q, strpos($q, '?')+1);
    echo $hello; // outputs 'world'
    

    考虑使用parse_str 第二个参数将数据保存在数组中,以避免覆盖局部变量。

    【讨论】:

      【解决方案3】:

      您可能希望使用 urldecode 并返回提取的变量,如下所示:

      ... some helper class...
      /**
      * Return parsed serialized JQuery object as PHP array of extracted variables
      */
      protected static function parseFields($encoded){
          parse_str(urldecode($encoded));
          unset($encoded);
          return get_defined_vars();
      }
      

      另外,您可能希望利用 JQuery 函数“$.param(data)”来创建 URL 编码字符串:

      var encoded=$.param(fields);
      

      并通过 AJAX/POST 请求向服务器提交到函数 parseFields()。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-09-19
        • 2018-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多