php url query nested array with no index

前端 未结 4 1145
清歌不尽
清歌不尽 2021-01-11 15:28

I\'m working with a third party API that receives several parameters which must be encoded like this:

text[]=Hello%20World&text[]=How%20are%20you?&ht         


        
4条回答
  •  执笔经年
    2021-01-11 16:32

    I very much agree with the answer by RiaD, but you might run into some problems with this code (sorry I can't just make this a comment due to lack of rep).

    First off, as far as I know http_build_query returns an urlencode()'d string, which means you won't have [ and ] but instead you'll have %5B and %5D.

    Second, PHP's PCRE engine recognizes the '[' character as the beginning of a character class and not just as a simple '[' (PCRE Meta Characters). This may end up replacing ALL digits from your request with '[]'.

    You'll more likely want something like this:

    preg_replace('/\%5B\d+\%5D/', '%5B%5D', http_build_query($params));
    

    In this case, you'll need to escape the % characters because those also have a special meaning. Provided you have a string with the actual brackets instead of the escapes, try this:

    preg_replace('/\[\d+\]/', '[]', $http_query);
    

提交回复
热议问题