Template Replace
PHP
Hard
7 views
Problem Description
You get n pairs key value, then one text line. Replace {key} with value and print final text.
Input Format
Line1 n. Next n lines: key value. Last line: text.
Output Format
One line text.
Sample Test Case
Input:
2
name Ravi
city Pune
Hello {name} from {city}!
Output:
Hello Ravi from Pune!
Official Solution
<?php
$inputText=stream_get_contents(STDIN);
$inputLines=preg_split('/\\R/', rtrim($inputText));
if(!$inputLines || trim($inputLines[0])==='') exit;
$n=intval(trim($inputLines[0]));
$mp=[];
$idx=1;
for($i=0;$i<$n;$i++){
$tokens=preg_split('/\\s+/', trim($inputLines[$idx++] ?? ''), 2);
$k=$tokens[0] ?? '';
$v=$tokens[1] ?? '';
if($k!=='') $mp[$k]=$v;
}
$text=$inputLines[$idx] ?? '';
foreach($mp as $k=>$v) $text=str_replace('{'.$k.'}', $v, $text);
echo $text;
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!