I currently do search and replace for a web page template like this:
$template = <<<TEMP
<html>
<head>
<title>[{pageTitle}]</title>
</head>
[{menuA}]
[{menuB}]
[{bodyContent}]
</html>
<<<TEMP;
The above is placed in a separate file.
Then, I do:
$template = str_replace("[{pageTitle}]",$pageTitle,$template);
$template = str_replace("[{menuA}]",$menuA,$template);
$template = str_replace("[{menuB}]",$menuB,$template);
$template = str_replace("[{bodyContent}]",$bodyContent,$template);
//Some 10 more similar to the above go here.
echo $template;
The problem is, there are some 15 in total just like the ones above.
Is there a better/cleaner/professional way to do this (either the search and replace, or do the entire thing differently). I find this very messy and unprofessional.
How to Find and Replace in Word on Windows. Click "Home," on the top-left side then "Replace" on the top-right side. Alternatively, use the keyboard shortcut Ctrl+H. Type the word or phrase you're looking for in the "Find what" box, and the replacement word or phrase in the "Replace with" box.
Yes, you can define array of things you want to replace and another array with things to replace with.
$array1 = array("[{pageTitle}]", "[{menuA}]");
$array2 = array($pageTitle, $menuA);
$template = str_replace($array1 , $array2 , $template);
By modifying ljubiccica's answer. You can create associative array with variables and values and then replace them:
$array=array(
'pageTitle'=>$pageTitle,
'menuA'=> $menuA,
);
$addBrackets = function($a)
{
return '[{'.$a.'}]';
};
$array1 = array_keys($array);
$array1 = array_map($addBrackets,$array1);
$array2 = array_values($array);
$template = str_replace($array1 , $array2 , $template);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With