To replace variables in string with their values defined in php, you can use the strtr() or preg_replace_callback() function.

Example with strtr()

- Click to select it.
<?php
// array with data for the variables added in string
$data = array(
  '{$site}'=>'http://coursesweb.net/',
  '{$year}'=>date('Y')
);
$str = 'Code-snippets from {$site} , added in: {$year}.';

$str2 = strtr($str, $data);
echo $str2;      // Code-snippets from http://coursesweb.net/ , added in: 2014.

Example with preg_replace_callback()

- Click to select it.
<?php
// array with data for the variables added in string
$data = array(
  'id'=>'test2',
  'domain'=>'CoursesWeb.net'
);
$str = '<div id="{$id}">Parse this string, interpret {$domain} </div>';


$str2 = preg_replace_callback('/{\$([^}]+)}/', function($m) {
  GLOBAL $data;
  return $data[$m[1]];
}, $str);

echo $str2;      // <div id="test2">Parse this string, interpret CoursesWeb.net </div>
- It is important to define data for variables into an Array with the keys that match the form you added the variable in string. Interpreting variables in string can also be useful to create and use template page; see this tutorial: Create and Use in PHP a Simple Template Page.

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
Interpret / Parse / Replace variable in string with value

Last accessed pages

  1. Display image file in Canvas, Check its type and size before Upload (642)
  2. Bubble Hit (107)
  3. addChild and removeChild (3398)
  4. Svetlograd Zuma (1161)
  5. PHP PDO - exec (INSERT, UPDATE, DELETE) MySQL (28165)

Top accessed pages

  1. Courses Web: PHP-MySQL JavaScript Ajax HTML CSS Flash-AS3 (45791)
  2. Read Excel file data in PHP - PhpExcelReader (34450)
  3. PHP-MySQL free course, online tutorials PHP MySQL code (34339)
  4. Get Attribute (ID, Class, Name, Title, Src) with jQuery (30919)
  5. PHP PDO - exec (INSERT, UPDATE, DELETE) MySQL (28165)