Home
PHP
Tech Tube
MySQL
Linux
CSS&HTML
JavaScript

Replace template variables

Simple but effective way to replace variabels in a template:
    /**
     * Replace parameters in a template with desired values
     *
     * @param string $template - The template that contains the placeholders
     * @param array $endpointParams - The parameters that should be replaced in the url
     * @param string $placeholderOpen - The string that marks the start of a placehodler
     * @param string $placeholderClose - The string that marks the end of a placehodler
     * @return string - The template with replaced placeholders
     */
    function replaceTemplateParams(string $template, array $params, string $placeholderOpen = '{{', string $placeholderClose = '}}')
    {
        $placeholders = array_map(function($placeholder) use ($placeholderOpen, $placeholderClose) { 
        	return $placeholderOpen . $placeholder . $placeholderClose;
        } , array_keys($params));
        return str_replace($placeholders, $params, $template);
    }
	
	// Examples of usage:
	
    echo replaceTemplateParams('/p1/{{val1}}/p2/{{val2}}', [
    	'val1' => 'One',
    	'val2' => 'Two',
    ]);
	
    echo replaceTemplateParams('/p1/%%val1%%/p2/%%val2%%', [
    	'val1' => 'One',
    	'val2' => 'Two',
    ], '%%', '%%');
    
    echo replaceTemplateParams('/p1/%%val1%%/p2/%%val2%%', [
    	'val1' => 'One',
    	'val2' => 'Two',
    ], '', '');