How to do the same in PHP?

`API_URL = "https://api.similarweb.com/v1/website/{site}/" \ "total-traffic-and-engagement/visits?api_key={api_key}" \ "&start_date={start_date}" \ "&end_date={end_date}" \ "&main_domain_only=false" \ "&granularity={granularity}".format( site='cnn.com', api_key=MY_API_KEY, start_date="2017-09", end_date="2017-10", granularity="monthly" )` 
  • You mean to substitute variables instead of {param} ? - Let's say Pie
  • Yes exactly. - Eugene
  • And you have data that is higher, they are in the form of a string? - Let's say Pie
  • Yes, in the form of lines. - Eugene
  • The last question, {value} must match its name? $value ? - Let's say Pie

1 answer 1

Well, as an option using eval :

 $string = 'API_URL = "https://api.similarweb.com/v1/website/{site}/" \ "total-traffic-and-engagement/visits?api_key={api_key}" \ "&start_date={start_date}" \ "&end_date={end_date}" \ "&main_domain_only=false" \ "&granularity={granularity}".format( site="cnn.com", api_key=MY_API_KEY, start_date="2017-09", end_date="2017-10", granularity="monthly" )'; $site = 'test.ru'; $api_key = 'superkey'; $start_date = 'ONE'; $end_date = 'TWO'; $granularity = 'variable'; preg_match_all('#\{(.*?)\}#', $string, $matches, PREG_SET_ORDER); foreach ($matches as $m) { eval('$string = str_replace($m[0], $'.$m[1].', $string);'); } echo $string; 

As a result, the data in the {параметр} format is replaced with the value of the $параметр

As a result, we get the following line:

 API_URL = "https://api.similarweb.com/v1/website/test.ru/" \ "total-traffic-and-engagement/visits?api_key=superkey" \ "&start_date=ONE" \ "&end_date=TWO" \ "&main_domain_only=false" \ "&granularity=variable".format( site="cnn.com", api_key=MY_API_KEY, start_date="2017-09", end_date="2017-10", granularity="monthly" ) 

UPD : The solution is slightly simpler:

 $string = str_replace('"', '\"', preg_replace('#\{(.*?)\}#i', '\$$1', $string)); eval('$string = "'.$string.'";'); echo $string; 

Or, instead of str_replace we’ll take addcslashes to escape quotes:

 eval('$string = "'.addcslashes(preg_replace('~\{(.*?)\}~i', '\$$1', $string), '"').'";'); echo $string; 
  • one
    Thank you for your help - Eugene
  • one
    @ Eugene, added another easier option, consider - Let's say Pie