In this lesson, you will learn how to format strings and work with functions to manipulate them. You will also learn the benefits and dangers of magic quotes.
Concatenation is a programming word for adding strings together. In PHP, the concatenation operator is a dot (.). Generally, concatenation is used to combine literal text with variables or values returned from functions. The example below illustrates this.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Concatenation</title>
</head>
<body>
<h1>Concatenation</h1>
<?php
$firstName = 'Paul';
$greeting = 'Hello';
echo $greeting . ' ' . $firstName . '!';
?>
<h2>Using Double Quotes to Avoid the Concatenation Operator</h2>
<?php
echo "$greeting $firstName!";
?>
<h2>Double quotes don't work when concatenating
the results of a function call</h2>
<?php
echo $greeting . ' ' . $firstName . '! Today is ' . date('l') . '.';
?>
</body>
</html>
As shown in the code, double quotes can be used to avoid using the concatenation operator. This works for concatenating literal strings with variables, but it does not work for concatenating values returned from functions. To do that, the function call must be outside of any quotes and combined with the rest of the string using the concatenation operator. This also is demonstrated in the code sample above.
| Function | Description |
|---|---|
trim()
|
Removes whitespace at beginning and end of a string. |
ltrim()
|
Removes whitespace at the beginning of a string. |
rtrim()
|
Removes whitespace at the end of a string. |
| Function | Description |
|---|---|
htmlentities()
|
Escapes all HTML entities. |
nl2br()
|
Inserts a <br /> tag before each newline character in a string. |
strtoupper()
|
Converts a string to uppercase. |
strtolower()
|
Converts a string to lowercase. |
ucfirst()
|
Converts the first character of a string to uppercase. |
ucwords()
|
Converts the first character of each word in a string to uppercase. |
| Function | Description |
|---|---|
explode()
|
Splits a string into an array on a specified character or group of characters. |
implode()
|
Converts an array into a string, placing a specified character or group of characters between each array element. |
join()
|
Same as implode(). |
| Function | Description |
|---|---|
substr(str,pos)
|
Returns the substring from the character in position pos to the end of the string. |
substr(str,-len)
|
Returns the substring from len characters from the end of the string to the end of the string. |
substr(str,pos,len)
|
Returns a len length substring beginning with the character in position pos. |
substr(str,pos,-len)
|
Returns a substring beginning with the character in position pos and chopping off the last len characters of the string. |
strstr(haystack,needle,before_needle)
|
If the third argument ( If the third argument ( The needle can be a string or an integer (or a number that can be converted to an integer). |
stristr(haystack,needle,before_needle)
|
Same as strstr(), but case insensitive. |
strpos(haystack,needle)
|
Finds the position of the first occurrence of a specified needle in a haystack (string). The needle can be a string or an integer (or a number that can be converted to an integer). |
strrpos(haystack,needle)
|
Finds the position of the last occurrence of a specified needle in a haystack (string). The needle can be a string or an integer (or a number that can be converted to an integer). |
str_replace()
|
Replaces all occurrences of one string with another string. |
| Function | Description |
|---|---|
strcmp()
|
Compares two strings. Returns < 0 if str1 is less than str2, > 0 if str1 is greater than str2, and 0 if they are equal. |
strcasecmp()
|
Like strcmp() but case insensitive. |
strlen()
|
Returns the length of a string. |
Below are some examples of string manipulation functions.
This example uses trim() and strtolower() to improve the form validation script.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Greeting Page</title>
</head>
<body>
<?php
$lastName = trim($_GET['LastName']);
$gender = strtolower(trim($_GET['Gender']));
if ($lastName == ' || $gender == ')
{
echo 'Error: You must fill out the form.
Please <a href="Greeting.html">try again</a>.';
}
else
{
switch($gender)
{
case 'male' :
echo "Hello Mr. $lastName!";
break;
case 'female' :
echo "Hello Ms. $lastName!";
break;
default :
echo "<b>$gender</b> is not a gender!";
}
}
?>
</body>
</html>
The htmlentities() function is used to escape HTML entities, such as less than signs (<) and greater than signs (>).
htmlspecialchars() is similar to htmlentities(). The differnce is that htmlentities() escapes all HTML entities, while htmlspecialchars() only escapes the most widely used. If you are interested in seeing the difference, take a look at Strings/Demos/EscapingSpecialChars.php.
Imagine if this form were submitted to the script below.
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>HTML Entities Processor</title> </head> <body> <h1>HTML Entities Processor</h1> <?php echo $_POST['UserComments']; ?> </body> </html>
This would result in the JavaScript code being executed. This JavaScript code would create a never-ending loop that popped up an alert over and over again. Although this would be pretty annoying, there are much worse things users could do, such as make a remote procedure call to execute a page on your server.
You can test this by opening Strings/Demos/HtmlEntitiesNotUsed.html and submitting the form. You probably don't want to test with a never-ending loop though.
This can easily be fixed by changing the code to look like this:
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>HTML Entities Processor</title> </head> <body> <h1>HTML Entities Processor</h1> <?php echo nl2br(htmlentities($_POST['UserComments'])); ?> </body> </html>
This script uses htmlentities() to escape all the HTML entities and uses nl2br() to convert newline characters to breaks. The resulting output looks like this:
And the resulting HTML source looks like this:
<html>
<head>
<title>HTML Entities Processor</title>
</head>
<body>
<h1>HTML Entities Processor</h1>
<script language="javascript"><br />
while (true)<br />
{<br />
alert("Try to get rid of me!");<br />
}<br />
</script></body>
</html>
The explode() function is used to convert a string to an array. The following form submits to Explode.php, the code of which is shown below.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Exploding Emails</title>
</head>
<body>
<?php
$emails = explode(';',$_POST['Emails']);
echo '<ol>';
foreach ($emails as $email)
{
echo '<li>' . trim($email) . '</li>';
}
echo '</ol>';
?>
</body>
</html>
Notice that the trim() function is used to trim the resulting elements of the array. This is because the string is exploded on the semi-colon only. If the user adds additional whitespace around the semi-colon, that whitespace will be part of the array element.
As shown earlier, the substr() function behaves differently depending on the values passed to it. The following screenshot shows the effects of using substr().
Like this PHP tutorial? Try our self-paced online PHP course, which includes videos and exercises in addition to the content in this PHP tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
There are two settings in the php.ini file that determine how PHP handles incoming data. The settings are magic_quotes_gpc (on by default) and magic_quotes_runtime (off by default).
The value of magic_quotes_gpc determines whether GET, POST and COOKIE data should be escaped "automagically". If magic_quotes_gpc is set to 1, then single quotes, double quotes and backslashes will be escaped with backslashes. In this case, if a user entered "O'Reilly" as her last name, and your script returned that value to the browser (e.g, echo $_POST['LastName'];), the value returned would read "O\'Reilly". You would need to strip the backslashes by passing the value through the stripslashes() function (e.g, echo stripslashes($_POST['LastName']);).
Although magic quotes can be useful, they can also cause confusion as the developer may not know whether magic quotes are turned on or off. To check whether they are on, use the get_magic_quotes_gpc() function as shown below.
if (get_magic_quotes_gpc())
{
echo stripslashes($_POST['LastName']);
}
else
{
echo $_POST['LastName'];
}
The value of magic_quotes_runtime determines whether data returned from files and databases should be escaped "automagically". It works similarly to magic_quotes_gpc.
Our recommendation on magic quotes is to turn them off in the php.ini file. You can easily escape a string when you need to with the addslashes() function.
Like this PHP tutorial? Try our self-paced online PHP courses, which includes videos and exercises in addition to the content in this PHP tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
This page was last updated on 2013-01-03
All pages and graphics in this PHP Tutorial is copyright 2013 and are the property of Webucator, Inc. unless otherwise specified. The purpose of this website is to help you learn PHP on your own and use of the website implies your agreement to our Terms of Service.