解析PHP中包含点的字符串 [英] Parse string containing dots in php

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

问题描述

我将解析以下字符串:

$str = 'ProceduresCustomer.tipi_id=10&ProceduresCustomer.id=1';                 
parse_str($str,$f);

我希望将$ f解析为:

I wish that $f be parsed into:

array(
    'ProceduresCustomer.tipi_id' => '10',
    'ProceduresCustomer.id' => '1'
)

实际上,parse_str返回

array(
        'ProceduresCustomer_tipi_id' => '10',
        'ProceduresCustomer_id' => '1'
    )

除了编写我自己的函数外,有人知道这是否有php函数吗?

Beside writing my own function, does anybody know if there is a php function for that?

推荐答案

来自

变量名中的点和空格将转换为下划线.例如,<input name="a.b" />变为$_REQUEST["a_b"].

因此,这是不可能的. parse_str()会将所有句点转换为下划线.如果您确实无法避免在查询变量名称中使用句点,则必须编写自定义函数来实现这一点.

So, it is not possible. parse_str() will convert all periods to underscores. If you really can't avoid using periods in your query variable names, you will have to write custom function to achieve this.

以下函数(取自此答案)将查询字符串中每个键值对的名称转换为它们对应的十六进制形式,然后在其上执行parse_str().然后,它们又恢复为原始形式.这样,句号就不会被触及:

The following function (taken from this answer) converts the names of each key-value pair in the query string to their corresponding hexadecimal form and then does a parse_str() on it. Then, they're reverted back to their original form. This way, the periods aren't touched:

function parse_qs($data)
{
    $data = preg_replace_callback('/(?:^|(?<=&))[^=[]+/', function($match) {
        return bin2hex(urldecode($match[0]));
    }, $data);

    parse_str($data, $values);

    return array_combine(array_map('hex2bin', array_keys($values)), $values);
}

示例用法:

$data = parse_qs($_SERVER['QUERY_STRING']);

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

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