开发者

php define variable inside str_replace array

I have a template system, that replaces text such as {HEADER} with the appropriate content. I use an array like this, that replaces the key with the value using str_replace.

$array = array("HEADER","This is the header");
    foreach($array as $var => $content) {开发者_开发技巧
       $template = str_replace("{" . strtoupper($var). "}", $content,$template);
    }

Now im trying to use a defined variable like this:

define("NAME","Site Name");

Inside the value for the header. So I want the defined variable to be inside the array which gets replaced so it would look like this, but it doesn't work.

$array = array("HEADER","Welcome to ".NAME."'s website!");

Any ideas? tell me if im not clear


Shouldn't your array line be:

$array = array("HEADER" => "Welcome to ".NAME."'s website!");

Since you are accessing the array items by key and value?


The way you are looping through the array, using :

foreach($array as $var => $content) {
    // ...
}

makes me think you should use an associative array for your $array.

i.e., it should be declared this way :

$array = array("HEADER" => "Welcome to ".NAME."'s website!");


And, as a demonstration, here's an example of code :

$template = <<<TPL
Hello, World !
{HEADER}
And here's the content ;-)
TPL;

define("NAME","Site Name");

$array = array("HEADER" => "Welcome to ".NAME."'s website!");
foreach($array as $var => $content) {
   $template = str_replace("{" . strtoupper($var). "}", $content,$template);
}

var_dump($template);

And the output I get it :

string 'Hello, World !
Welcome to Site Name's website!
And here's the content ;-)' (length=73)

Which indicates it's working ;-)
(It wasn't, when $array was declared the way you set it)


When using this :

$array = array("HEADER","This is the header");
var_dump($array);

You are declaring an array that contains two items :

array
  0 => string 'HEADER' (length=6)
  1 => string 'This is the header' (length=18)


On the other hand, when using this :

$array = array("HEADER" => "This is the header");
var_dump($array);

You are declaring an array that :

  • contains only one item
  • "HEADER" being the key
  • and "This is the header" being the value

Which gives :

array
  'HEADER' => string 'This is the header' (length=18)


When using foreach ($array as $key => $value), you need the second one ;-)


And, purely for reference, you can take a look at, in the manual, the following pages :

  • Arrays
  • foreach
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜