Replace values in a URI query string

后端 未结 2 1284
故里飘歌
故里飘歌 2020-12-01 22:42

I have part of a query string that I want to make a replacement in. I want to use preg_replace but am kind of hung up on the regex.

Can someone please

相关标签:
2条回答
  • 2020-12-01 23:20

    You can use parse_str as was mentioned already.
    In addition, if you want to put them back into a query string you can use http_build_query

    Example:

    parse_str('bikeType=G&nikeNumber=4351', $params);
    $params['bikeType'] = 'F';
    $params['nikeNumber'] = '1234';
    echo http_build_query($params, '', '&'); 
    

    Output

    bikeType=F&nikeNumber=1234
    

    Please note that you should not use parse_str without the second argument (or at least not with some consideration). When you leave it out, PHP will create variables from the query params in the current scope. That can lead to security issues. Malicious users could use it to overwrite other variables, e.g.

    // somewhere in your code you assigned the current user's role
    $role = $_SESSION['currentUser']['role'];
    // later in the same scope you do
    parse_str('bikeType=G&nikeNumber=4351&role=admin');
    // somewhere later you check if the user is an admin
    if($role === "admin") { /* trouble */ }
    

    Another note: using the third param for http_build_query is recommended, because the proper encoding for an ampersand is &. Some validators will complain if you put just the & in there.

    0 讨论(0)
  • PHP has a convenient function to parse query strings: parse_str(). You might want to take a look at that or provide more details as your question isn't exactly clear.

    0 讨论(0)
提交回复
热议问题