views:

83

answers:

6

Could you tell how to replace string by preg-replace (need regular expression):

/user/{parent_id}/{action}/step/1

At the equivalent values of an array:

array('parent_id'=>32, 'action'=>'some');

To make:

/user/32/some/step/1

Addition

This is a typical problem, so I probably will not know what the names of variables come

A: 
$s = '/user/{parent_id}/{action}/step/1';
$replacement = array('parent_id'=>32, 'action'=>'some');
$res = preg_replace(array('/\\{parent_id\\}/', '/\\{action\\}/'), $replacement, $s);

Of course, you could just as well use str_replace (in fact, you ought to).

Artefacto
+2  A: 
$arr = array('parent_id'=>32, 'action'=>'some');

$out = str_replace(array_keys($arr),array_values($arr),$in);

no need for regexps!

mvds
This won't replace the brackets...
Daniel Vandersluis
Damn... left as an excercise to the reader then ;-)
mvds
+3  A: 

You can use str_replace

For example:

str_replace(array("{parent_id}", "{action}"), array(32, 'some'), "/user/{parent_id}/{action}/step/1");
antyrat
This is a typical problem, so I probably will not know what the names of variables come
HWTech
Can you provide data that you will be know? It may help me to modify my answer.
antyrat
+1  A: 
<?php
  $string = '/usr/{parent_id}/{action}/step/1';
  $pattern = array('#{parent_id}#', '#{action}#');
  $values = array('32', 'some');

  echo preg_replace($pattern, $values, $string);
?>

If your problem is not more complicated than this, i would recommend changing preg_replace to str_replace though.

EDIT: I see you don't know the variable names in advance. In which case you could do something like this.

<?php
  function wrap_in_brackets(&$item)
  {
    $item = '{' . $item . '}';
    return true;
  }

  $string = '/usr/{parent_id}/{action}/step/1';
  $variables = array('parent_id' => 32, 'action' => 'some');

  $keys = array_keys($variables);
  array_walk($keys, 'wrap_in_brackets');
  echo str_replace($keys, array_values($variables), $string);
?>
Brandon Horsley
+2  A: 

Say you have:

$arr = array('parent_id'=>32, 'action'=>'some');
$in =  '/usr/{parent_id}/{action}/step/1';

This will replace the braces:

function bracelize($str) {
    return '{' . $str . '}';
}    

$search = array_map('bracelize', array_keys($arr));
$out = str_replace($search, $arr, $in);

Or if you are using PHP >= 5.3 you can use lambdas:

$search = array_map(function ($v) { return '{'.$v.'}';}, array_keys($arr));
$out = str_replace($search, $arr, $in);
quantumSoup
A: 

Expanding on mvds' answer:

$in  = 'user/{parent_id}/{action}/step/1';
$arr = array('{parent_id}' => 32, '{action}' => 'some');
$out = str_replace(array_keys($arr), $arr, $in);

Or:

$in    = 'user/{parent_id}/{action}/step/1';
$arr   = array('parent_id' => 32, 'action' => 'some');
$arr[] = '';
$find  = array_merge(array_keys($arr), array('{', '}'));
$out   = str_replace($find, $arr, $in);
GZipp