zeropsi
zeropsi

Reputation: 694

Replacing array variables in string with preg_replace

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?

Upvotes: 2

Views: 238

Answers (2)

iam-decoder
iam-decoder

Reputation: 2564

why not do something like this?

$params = array(
    'type' => 'butter',
    'color' => 'yellow',
    'taste' => 'good',
    'content' => 'low-fat'
);
$query = http_build_query($params);

Upvotes: 0

anubhava
anubhava

Reputation: 785246

You need to use preg_replace_callback for this:

$val = preg_replace_callback('/\$params\[(\d+)\]/', function ($m) use ($params)
      { return $params[$m[1]]; }, $query);
//=> type=butter&color=yellow&taste=good&content=low-fat

Upvotes: 2

Related Questions