String interpolation is a common feature in many programming languages such as Ruby, PHP, Perl, ColdFusion, etc. It means to insert a string or replace a variable with its value. It makes string formatting and specifying contents more intuitive.[1]
Examples
PHP
<?php
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
class foo
{
var $foo;
var $bar;
function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'Jason';
echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>
The output will be:
My name is "Jason". I am printing some Foo.
Now, I am printing some Bar2.
This should print a capital 'A': A
Perl
#!/usr/bin/perl
use strict;
use warnings;
my $apples = 4;
print "I have $apples apples\n";
The output will be:
I have 4 apples
ColdFusion
<!--- variable and expressions can be added during string creation and output --->
<cfset name = "Dan" />
<cfset fruit = ['apples', 'pears', 'bananas'] />
<cfset phrase = "I have #arraylen(fruit)# types of fruit, such as #fruit[1]#" />
<cfoutput>
<p>Hi #Dan#,</p>
<p>I just wanted to let you know #phrase#.</p>
<p>Types:</p>
<ul>
<cfloop array="#fruit#" index="type">
<li>#type#</li>
</cfloop>
</ul>
</cfoutput>
Ruby
apples = 4
puts "I have #{apples} apples"
# or
puts "I have %s apples" % apples
The output will be:
I have 4 apples
BOO
apples = 4
print("I have $(apples) apples")
// or
print("I have {0} apples" % apples)
The output will be:
I have 4 apples
CoffeeScript
apples = 4
console.log "I have #{apples} apples"
The output will be:
I have 4 apples
Python
apples = 4
print "I have %s apples" % apples
The output will be:
I have 4 apples
Security Issues
String Interpolation, like string concatenation, may lead to security problems. When failed to properly escape or filter user input data, system will expose to SQL Injection, Script Injection, XML External Entity Injection (XXE), and Cross Site Scripting (XSS) attacks.[2]
An example of SQL Injection will be like this:
query = "SELECT x, y, z FROM Table WHERE id= '$id'
If id is replaced with "'; DELETE FROM Table WHERE = '", executing this query will wipe out all the data on the local machine.