I wish to have one string that contains for instance (mystring):
file config.php
$mystring = "hello my name is $name and i got to $school";
file index.php
include('config.php');
$name 开发者_StackOverflow= $_GET['name'];
$school = $_GET['school'];
echo $mystring;
Would this work ? or are there any better ways
$string = 'Hello, my name is %s and I go to %s';
printf($string, $_GET['name'], $_GET['school']);
or
$string = 'Hello, my name is :name and I go to :school';
echo str_replace(array(':name', ':school'), array($_GET['name'], $_GET['school']), $string);
You can automate that last one with something like:
function value_replace($values, $string) {
return str_replace(array_map(function ($v) { return ":$v"; }, array_keys($values)), $values, $string);
}
$string = 'Hello, my name is :name and I go to :school';
echo values_replace($_GET, $string);
No it won't work.
You have to define $name
first before using it in another variable
config.php should look like
<?php
$name = htmlspecialchars($_GET['name']);
$school = htmlspecialchars($_GET['school']);
$mystring = "hello my name is $name and i got to $school";
and index.php like
<?php
include('config.php');
echo $mystring;
Why didn't you try it?
demo: http://sandbox.phpcode.eu/g/2d9e0.php?name=martin&school=fr.kupky
Alternatively, you can use sprintf like this:
$mystring = "hello my name is %s and i got to %s";
// ...
printf($mystring, $name, $school);
This works because your $mystring literal is using double quotes, if you'd used single quotes then it would not work.
http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing
精彩评论