String Manipulation

In this lesson of the PHP tutorial, you will learn...
  1. To format strings.
  2. To work with string manipulation functions.
  3. To make strings safe for outputting to the browser.
  4. To understand the benefits and dangers of magic quotes.

Formatting Strings

Concatenation

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.

Code Sample: Strings/Demos/Concatenation.php

<html>
<head>
<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>
Code Explanation

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.

String Manipulation Functions

Trimming Strings
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.
Presentation
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.
Converting Strings and Arrays
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().
Substrings
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() Returns the position of one string in another.
stristr() Returns the position of one string in another. Case insensitive.
strpos() Finds the position of the first occurrence of a specified character in a string.
strrpos() Finds the position of the last occurrence of a specified character in a string.
str_replace() Replaces all occurrences of one string with another string.
Comparing Strings
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.

Examples of String Functions

Below are some examples of string manipulation functions.

trim() and strtolower()

This example uses trim() and strtolower() to improve the form validation script.

Code Sample: Strings/Demos/Greeting.php

<html>
<head>
 <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>

htmlentities() and nl2br()

The htmlentities() function is used to escape HTML entities, such as less than signs (<) and greater than signs (>). Take a look at the screenshot below to get an idea of why this is important.

Imagine if this form were submitted to the script below.

Code Sample: Strings/Demos/HtmlEntitiesNotUsed.php

<html>
<head>
<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.

This can easily be fixed by changing the code to look like this:

Code Sample: Strings/Demos/HtmlEntitiesUsed.php

<html>
<head>
<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>
&lt;script language=&quot;javascript&quot;&gt;<br />
  while (true)<br />
  {<br />
    alert(&quot;Try to get rid of me!&quot;);<br />
  }<br />
&lt;/script&gt;</body>
</html>

explode()

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.

Code Sample: Strings/Demos/Explode.php

<html>
<head>
<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.

substr()

As shown earlier, the substr() function behaves differently depending on the values passed to it. The following screenshot shows the effects of using substr().

Magic Quotes

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).

magic_quotes_gpc

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'];
}

magic_quotes_runtime

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.

Recommendation on Magic Quotes

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.

Conclusion

In this lesson of the PHP tutorial, you have learned to format strings safely for outputting to the browser, to work with PHP's built-in string manipulation functions to improve form validation, and to understand how magic quotes work.

To continue to learn PHP go to the top of this page and click on the next lesson in this PHP Tutorial's Table of Contents.

Use of this website implies agreement to the following:

Copyright Information

All pages and graphics on this Web site are the property of Webucator, Inc. unless otherwise specified.

None of the content on this website may be redistributed or reproduced in any way, shape, or form without written permission from Webucator, Inc.

No Printing or saving of web pages

This content may not be printed or saved. It is for online use only.


Linking to this website

You may link to any of the pages on this website; however, you may not include the content in a frame or iframe without written permission from Webucator, Inc.


Warranties

This website is provided without warranty of any kind. There are no guarantees that use of the site will not be subject to interruptions. All direct or indirect risk related to use of the site is borne entirely by the user. All code and explanations provided on this site are provided without warranties to correctness, performance, fitness, merchantability, and/or any other warranty (whether expressed or implied).

For individual private use only

You agree not to use this online manual to deliver or receive training. If you are delivering or attending a class that is making use of this online manual, you are in violation of our terms of service. Please report any abuse to courseware@webucator.com. If you would like to deliver or receive training using this manual, please fill out the form at http://www.webucator.com/Contact.cfm.