开发者

Could you tell how to replace by regular expression

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


You can use str_replace

For example:

str_replace(array("{parent_id}", "{action}"), array(32, 'some'), "/user/{parent_id}/{action}/step/1");


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

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

no need for regexps!


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);


$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).


<?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);
?>


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜