Hello!

A question.

There is a line, say item.php? Dswdfwef = {param1} & 4545h45h = {param2} ...

There is an array

array( 'param1' => 'пока', 'param2' => 'привет', 'param3' => ) 

I need to replace {param1} and {param2} in the line with the corresponding values ​​from the array by keys. It is clear that it is possible through str_replace (I have a certain set of parameters).

Somehow you can without str_replace, so automatically and beautifully))

    2 answers 2

    This option will come down? True, at the expense of "being so automatic and beautiful " - not sure;)

     $str = 'item.php?dswdfwef={param1}&4545h45h={param2}'; $new_vals = array( 'param1' => 'пока', 'param2' => 'привет', 'param3' => '' ); parse_str($str, $output); $result = array(); foreach($output as $k => $v){ $v = trim($v,'{}'); if(isset($new_vals[$v]) && !empty($new_vals[$v])){ $result[$k] = $new_vals[$v]; } else { // если нужно сохранить пару без замещений // в противном случае - убрать else $result[$k] = $v; } } echo urldecode(http_build_query($result)); // item_php?dswdfwef=пока&4545h45h=привет 
    • Hm It turns out that item_php, not item.php. The same if the domain is specified in the line. This parse_str gets up. - drop_off
    • one
      @drop_off, yes. Case hand urldecode () . Then it is necessary to disassemble into parts using [parse_url ()] [1]. Those. The request part is as follows: $ uri = 'item.php? dswdfwef = {param1} & 4545h45h = {param2}'; $ path = parse_url ($ uri, PHP_URL_PATH); // item.php $ query = parse_url ($ uri, PHP_URL_QUERY); // after the "?" $ query - obabatyvay and continue to collect everything together. By the way, if the URI can also contain "host", then it will also need to be taken into account [1]: ua2.php.net/manual/ru/function.parse-url.php - Deonis
    • To me, $ output returns such a string already, before urldecode. I got the point. Now I’ll try with parse_url () - drop_off
    • @drop_off, just for the sake of interest - why do you need it? I do not like regulars, but in this case, I still prefer str_replace or something like that, because much less unnecessary "gestures". - Deonis
    • In general, a person adds access settings and links to specific sites. In the link, replaces the parameter values ​​with {...} tags. In view of the fact that some parameters are dynamic (they are not taken from the settings), then everything can not be immediately substituted. For this, I decided that the replacement of the values ​​of the parameters in the link will be immediately from the user's side, and in PHP I will automatically replace everything as it should and be processed. I just don’t know exactly how many parameters there will be, and I wanted it automatically, but not through str_replace, so as not to pick the code ... - drop_off

    There is a standard function for building a request - http_build_query

    • Did not understand how to use? I get the string from the database (saved in this form) - drop_off