phpstringurlreplacequery-string

Change the first element of a querystring in a full URL string


How can I use str_replace method for replacing a specified portion(between two substrings). For example,

string1="www.example.com?test=abc&var=55";
string2="www.example.com?test=xyz&var=55";

I want to replace the string between '?------&' in the url with ?res=pqrs&. Are there any other methods available?


Solution

  • Dirty version:

    $start = strpos($string1, '?');
    $end = strpos($string1, '&');
    
    echo substr($string1, 0, $start+1) . '--replace--' . substr($string1, $end);
    

    Better:

    preg_replace('/\?[^&]+&/', '?--replace--&', $string1);
    

    Depending on whether you want to keep the ? and &, the regex can be mofidied, but it would be quicker to repeat them in the replaced string.