1

I have a string that looks a little something like this:

$string = 'var1=foo&var2=bar&var3=blahblahblah&etc=etc';

And I would like to make another string from that, and replace it with a value, so for example it will look like this

$newstring = 'var1=foo&var2=bar&var3=$myVariable&etc=etc'; 

so var3 in the new string will be the value of $myVariable.

How can this be achieved?

2 Answers 2

3

No need for regex; built in URL functions should work more reliably.

// Parse the url first
$url = parse_url($string);

// Parse your query string into an array
parse_str($url['query'], $qs);

// Replace the var3 key with your variable
$qs['var3'] = $myVariable;

// Convert the array back into a query string
$url['query'] = http_build_query($qs);

// Convert the $url array back into a URL
$newstring = http_build_url($url);

Check out http_build_query and parse_str. This will append a var3 variable even if there isn't one, it will URL encode $myVariable, and its more readable than using preg_replace.

Sign up to request clarification or add additional context in comments.

1 Comment

Well, my string actually has a URL in it; example.com/…
0

You can use the method preg_replace for that. Here comes an example

<?php

$string = 'var1=foo&var2=bar&var3=blahblahblah&etc=etc';
$var = 'foo';

echo preg_replace('/var3=(.*)&/', 'var3=' . $var . '&', $string);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.