2

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?

2
  • While the design is overall wrong, your preg_replace call has the parameters in the wrong order. The third parameter is the original string that you are manipulating. Commented Jun 26, 2015 at 19:25
  • 1
    To do a replacement for a key/value, I think you have to capture the key, and use it to reference the replacement value. \$params\[([1-9]+[0-9]*)\] Commented Jun 26, 2015 at 19:28

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for this. Can you explain the difference between /\$params\[(\d+)\]/ and my original (\$params\[[1-9]+[0-9]*\])?
You regex is capturing $params[1] where mine is just capturing 1. We just need number to get the indexed value from array params
0

why not do something like this?

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

1 Comment

I was attempting to use a predefined format in a string. I wanted to match the paramaters passed from the URL to that string, to create my variables.

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.