Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better way to do this search and replace for a template

Tags:

replace

php

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.

like image 397
Norman Avatar asked Apr 25 '13 11:04

Norman


People also ask

How do you do search and replace in word?

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.


2 Answers

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);
like image 105
ljubiccica Avatar answered Oct 05 '22 14:10

ljubiccica


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);
like image 42
Narek Avatar answered Oct 05 '22 13:10

Narek