Difference between revisions of "Working with Strings and Text in PHP"

From Techotopia
Jump to: navigation, search
(PHP fprintf formatting specifiers)
(PHP fprintf formatting specifiers)
Line 164: Line 164:
 
* '''+'''  - Forces both + or - in front of numbers. By default, only negative numbers display their sign.
 
* '''+'''  - Forces both + or - in front of numbers. By default, only negative numbers display their sign.
  
* ''''n - Specifies what to use as padding (n). Used in conjunction with the width specifier and defaults to space. Eg: %'_20s specified that '_' should be used as padding)
+
* ''''n''' - Specifies what to use as padding (n). Used in conjunction with the width specifier and defaults to space. Eg: %'_20s specified that '_' should be used as padding)
  
 
* '''-''' Left-justifies the value
 
* '''-''' Left-justifies the value

Revision as of 14:16, 4 June 2007

Given that PHP is essentially a vehicle for the deployment of web content, and that much web content is text based, it should come as no surprise that PHP includes a range of features designed to ease the task of manipulating text and strings.

In this chapter we will explore a number of the functions and techniques provided by PHP to enable you, as a web developer, to perform tasks such as changing the case of a string, replacing one part of a piece of text with another peice of text, searching text and much more.


Contents


Changing the Case of a PHP String

PHP provides a number of functions that enable changes to be made to the case of text contained in a string. These functions all take the string to be modified as an argument and return the modifed string. It is important to note that these functions are nondestructive, that is to say they do not make any change to the original string, they simply return a completely new string containing the modification leaving the orignal string unaltered. The returned string can be assigned to a new variable or used directly in another function (such as a print or echo):

<?php
$myString = "This is a test string.";

$newString = strtoupper($myString);     // Assign converted string to a new variable

echo strtolower($myString);             // Use retruned string in a eacho statement
?>

If a change to the original string is required (as opposed to assigning the modified version to a new variable) the returned string can simply be assigned to the original variable:

<?php
$myString = "This is a test string.";

$myString = strtoupper($myString);     // Assign converted string to the orignal variable

?>

The PHP string functions designed to change the case of a string are listed below with descriptions:

  • strtolower() - Converts entire string to lowercase
  • strtoupper() - Converts entire string to uppercase
  • ucfirst() - Converts the first letter of the sentence to uppercase
  • ucwords() - Converts the first letter of every word to uppercase

Converting to and from ASCII Values

PHP provides the ability to work with ASCII (American Standard Code for Infomration Interchange) values. ASCII maps numerical character codes to standard, human readable characters. There are 127 ASCII characters representing the letters of the alphabext (including upper and lower case), numbers and various punctuation marks. There is also an extended character set which contains 255 characters.

PHP provides two functions for the purpose of converting to and from ASCII codes:

  • ord() - Takes a character as an argument and returns the ASCII code corresponding to that character.
  • chr() - Takes an ASCII code as an argument and retuns the character equivalent.

The following example converts a character to an ASCII code and then reverts it back to the character:

<?php
$character = 'A';

$asciicode = ord($character);

echo "The ASCII code for $character is " . $asciicode . '<br>';

$char = chr($asciicode);

echo "The character for ASCII code for $asciicode is " . $char . '<br>';

?>

When executed the above code will produce the following output:

The ASCII code for A is 65
The character for ASCII code for is A

Printing Formatting Strings in PHP

Those familar with other programming langusges such as C and C++ will probably be familiar with the concept of formatting strings and the printf() function. The printf function allows strings to constructed which contain variables and provides a number of formatting options for those variables.

Essentially printf allows you to specify a string and define how particular variables are to be embedded in that string. fprintf() takes two or more arguments and takes the the following form:

fprintf ( "String", variable1, variable2, ... );

The String represents the string that is to displayed and contains the formatting specifiers. The variables specify the variables that are to be substituted inplace of the respective formatting rules.

PHP fprintf formatting specifiers

The formatting specifiers begin with a '%' character following by a latter to indicate the type of variable to be displayed. For example a string is represented by %s. Optional rules can be placed between the '%' and the type to control formatting.

The following table lists the variable types and the corresponding letter to use when constructing the formatting rule:

SpecifierDescription
%%Displays a percent sign
%bA integer represnted as a binary number
%cA character based on the ASCII value
%dA signed decimal number
%eScientific notation (for example 1.2e+2)
%uAn unsigned decimal number
%fA floating-point number
%FFloating-point number
%oAn octal number
%sA String
%xHexadecimal number in lowercase letters
%XHexadecimal number in uppercase letters

Before we look at the formatting options we first need to see some of the above rules in action. Let's begin by embedding a string variable into a PHP printf function call:

<?php
$myColor = "Green";

printf("My favorite color is %s.", $myColor);

?>

In the above example the %s will be replaced by the value of $myString to create a string which reads:

My favorite color is Green.

We can now consider creating an printf statements which combines a number of differnet formatting rules:

<?php
$myColor = "Green";
$myNumber = 12;

printf("My favorite color is %s and my lucky number is %d.", $myColor, $myNumber);

?>

In the above example the %s will be replaced by the value of $myString and the %d will be replaced by the decimal value of $myNumber to create a string which reads:

My favorite color is Green and my lucky number is 12.

Suppose we wanted to display our lucky number as a hexadecimal value. All we would need to do is replace the %d with a %x:

$formatted = printf ("My favorite color is %s and my lucky number is %x.", $myString);

thereby generating the following output:

My favorite color is Green and my lucky number is c.

Finally we need to look at the formatting options which may be specified after the '%' caharacter.

  • + - Forces both + or - in front of numbers. By default, only negative numbers display their sign.
  • 'n - Specifies what to use as padding (n). Used in conjunction with the width specifier and defaults to space. Eg: %'_20s specified that '_' should be used as padding)
  • - Left-justifies the value
  • [0-9] Specifies the minimum width to be used by the variable - use din conjuction with the padding character
  • .[0-9] Specifies the number of decimal digits or maximum string length

As always some examples will hopefully help to clarify these options:

To limit a floating point number to 2 decimal places:

<?php

$myColor = "Green";
$myNumber = 12.2089987;
printf("My number is %.2f.", $myNumber);

?>

To pad the formatting with '_' characters to a width of 12 characters:

<?php

$myNumber = 12.2089987;
printf("My number is %'_12f.", $myNumber);

?>

resulting in the following output:

My number is ___12.208999.