Soojoo
Soojoo

Reputation: 2156

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?

Upvotes: 0

Views: 101

Answers (4)

Ja͢ck
Ja͢ck

Reputation: 173542

Since you're working with URL's, you can decompose the URL first, remove what you need and put it back together like so:

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

// fetch the part after ?
$qs = parse_url($string1, PHP_URL_QUERY);

// turn it into an associative array    
parse_str($qs, $a);
unset($a['test']); // remove test=abc
$a['res'] = 'pqrs'; // add res=pqrs

// put it back together
echo substr($string1, 0, -strlen($qs)) . http_build_query($a);

There's probably a few gotchas here and there; you may want to cater for edge cases, etc. but this works on the given inputs.

Upvotes: 1

CAMason
CAMason

Reputation: 1122

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.

Upvotes: 0

JNF
JNF

Reputation: 3730

Think of regex

<?php
$string = 'www.example.com?test=abc&var=55';
$pattern = '/(.*)\?.*&(.*)/i';
$replacement = '$1$2';
$replaced = preg_replace($pattern, $replacement, $string);
?>

Upvotes: 0

Jon
Jon

Reputation: 437336

You could use preg_replace to do that, but is that really what you are trying to do here?

$str = preg_replace('/\?.*?&/', '?', $input);

If the question is really "I want to remove the test parameter from the query string" then a more robust alternative would be to use some string manipulation, parse_url or parse_str and http_build_query instead:

list($path, $query) = explode('?', $input, 2);
parse_str($query, $parameters);
unset($parameters['test']);
$str = $path.'?'.http_build_query($parameters);

Upvotes: 2

Related Questions