Tutorial :Could you tell how to replace by regular expression



Question:

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


Solution:1

$arr = array('parent_id'=>32, 'action'=>'some');    $out = str_replace(array_keys($arr),array_values($arr),$in);  

no need for regexps!


Solution:2

You can use str_replace

For example:

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


Solution:3

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


Solution:4

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


Solution:5

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


Solution:6

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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »