user393273
user393273

Reputation: 1438

Update variables already embedded in a string

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 = $_GET['name'];
$school = $_GET['school'];

echo $mystring;

Would this work ? or are there any better ways

Upvotes: 0

Views: 339

Answers (4)

genesis
genesis

Reputation: 50982

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

Upvotes: 3

deceze
deceze

Reputation: 522520

$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);

Upvotes: 6

Steve Claridge
Steve Claridge

Reputation: 11090

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

Upvotes: -4

Tomas Kohl
Tomas Kohl

Reputation: 1388

Alternatively, you can use sprintf like this:

$mystring = "hello my name is %s and i got to %s";
// ...
printf($mystring, $name, $school);

Upvotes: 2

Related Questions