Help writing RegEx statement

I am trying to use RegEx to replace an arrays value in a string that I have created.

For example:

$params = array(1 => 'butter', 2 => 'yellow', 3 => 'good', 4 => 'low-fat');
$query = 'type=$params[1]&color=$params[2]&taste=$params[3]&content=$params[4]';

I wanted to use preg_replace to replace all of the $params in the $query with the actual values for the string.

I had originally attempted:

$query = preg_replace("(\$params\[[1-9]+[0-9]*\])",$query,$params);

But that seemed to create an array for $query.

I was hoping to get:

$query =  'type=butter&color=yellow&taste=good&content=low-fat';

Any ideas where I am going wrong?

You don’t need to use preg_replace for that. If you enclose your $query string in double-quotes, PHP will automatically substitute the values for any variables in the string:

$params = array(1 => 'butter', 2 => 'yellow', 3 => 'good', 4 => 'low-fat');
$query = "type=$params[1]&color=$params[2]&taste=$params[3]&content=$params[4]";
// result: type=butter&color=yellow&taste=good&content=low-fat

However, rather than building up query strings manually, you could always pass an associative array to the http_build_query function, which will do it for you:

$params = array('type' => 'butter', 'color' => 'yellow', 'taste' => 'good', 'content' => 'low-fat');
echo http_build_query($params);
// result: type=butter&color=yellow&taste=good&content=low-fat
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.