June 7, 2011, 11:33 a.m.
posted by romcheg
Because you're working with essentially two languages that both support manipulating strings, you need to learn about string functions in PHP and MySQL. You may find it more appropriate to modify a string either in a query or in PHP, based on the particular situation. You're going to learn about the following string operations:
We'll start with formatting strings, since that will help you throughout the rest of the topics.
Formatting Strings for Display
So far, you've been using echo and print to display strings without any modification. You'll learn about two functions called printf and sprintf. If you're familiar with other programming languages, such as C, you'll recognize that these functions work the same way as they do elsewhere. Don't worry if you haven't used them beforethey're not too hard to work with. The only difference between the two is that printf displays a formatted string to the output like print does, while sprintf saves the string it builds as another string with a name specified by you.
The printf function works by taking as its first parameter a special formatting string. The formatting string works like a template to describe how to plug in the rest of the parameters into one resulting string. You can specify details such as how to format numbers in the string or the padding of values. Each parameter that's placed into the resulting string has a placeholder in the formatting string. For example, to output a binary number, you use the code in Figure.
Displaying a number in binary format
This code then produces the output shown in Figure.
Displaying 42 in binary format
The formatting string in Figure contains a placeholder that specifies where to put the second parameter of 42. It begins with a percent sign (%), which is called the conversion specification. There can be any number of conversion specifications in the formatting string, but they must each have a corresponding parameter when printf is called.
The character after the percent sign is the type specifier. The type specifier defines how the parameter is formatted for display when it's placed in the output string, as demonstrated in Figure.
printf puts the numbers into the string
Including two numbers in the string
So far, the only type specifier we've used is b for binary, but there are more. Figure lists numeric type specifiers.
Displaying the same number in different formats
Figure gives you this column:
42 101010 * 42.000000 52 42 2a 2A
In practice, you might use this to convert from an integer to a hexadecimal number if you're building a string when specifying colors in HTML elements. Since you tend to relate better to the decimal value, you can use decimals and have them automatically formatted correctly for display in a tag such as color="#2a11cc".
You can also specify padding for each field. To left pad a field with zeros, place a zero after the conversion specification percent sign (%) followed by the number of zeros to pad the type specifier, as shown in Figure. If the output of the parameter uses fewer spaces than the number you specify, zeros are filled in on the left.
Using left zero padding
Padding with zeros gives you the result shown in Figure.
Zero padding to five spaces
Padding with leading spaces, shown in Figure, works the same way, except you specify a space after the percent sign instead of a zero.
Using left space padding
Using the left space padding displays the screen shown in Figure.
Left padding doesn't show up correctly
As you can see in Figure, the spacing before 42 was ignored by the web browser. You can fix that by using the HTML <pre> tag. The <pre> HTML markup is used to enclose preformatted text. In the tag, all spaces and line breaks are rendered literally. Additionally, the <pre> text renders in a fixed-pitch font. See Figure.
Adding the <pre> and </pre> tags so the spaces display
In Figure, we correctly see the spaces.
The spaces show up now
Left padding using the default of spaces
Still left padded
To right pad fields, simply put a negative number in the padding field, as in Figure.
Right padding with spaces
And the output from the negative number in the padding field displays Figure.
Padding on the right
Sometimes you'll want to change how many digits appear after a decimal point for a real (floating-point) number. This is especially true if you need to print in currency format. To specify the number of digits to use after the decimal point, use a conversion specifier that has a decimal point after the percentage sign followed by the number of decimals. For example, the following code shows you how to do it:
Figure shows a value of 42.4242 set to display as currency.
Displaying a real number in money format
Our code displays with the dollar sign and decimal correctly, as shown in Figure.
Only two decimal points display
Even if you replace the value of 42.4242 with 42, Figure would still print two zeros after the decimal point, since you told printf that you always want to print two digits after the decimal point.
Please pay $42.00.
Figure breaks apart the conversion specifier %08.2f.
The segments of a conversion specifier
The conversion specification in Figure means that you'll print the floating-point number left padded with zeros to eight total spaces. There'll be two digits after the decimal place.
The sprintf function works exactly the same way as print, except its output is sent to a string.
In Figure, the output string is assigned to the variable $total. From there, it could be used in further processing or, in this case, printed to the screen using echo.
Using sprintf with a variable
Figure displays the result.
The output of the $total variable
Sometimes you'll be working with strings that come from external sources, so you'll need to find out information about them. This information might include whether they contain certain strings or may simply be their length. Remember that strings are more or less ordered lists of characters. Think of specific characters in a string as an exact numeric location of the string.
The PHP function strlen can be used to find out how many characters are in a string. This is very useful for validating that there's data in a string, and that a string isn't larger than it should be. Figure shows how to use this.
Calculating the length of a string
Our password code above displays the screen in Figure.
The password wasn't long enough to be secure
We're going to discuss changing the case of a string next. If you recall, this was an important bullet point when we started talking about string functions.
PHP provides functionality for changing the case of a string to all uppercase, all lowercase, or the first letter of a word to uppercase. The commands are strtoupper, strtolower, and ucwords, respectively. Figure uses each of them with the same string.
Using the word case functions
The code in Figure displays lowercase, uppercase, and other details.
John Doe in upper case is JOHN DOE. John Doe in lower case is john doe. John Doe in first letter upper case is John Doe.
Number and other symbols are not affected.
Using strtoupper returns strings with all alphabetic characters converted to uppercase. Whereas strtolower returns a string with all alphabetic characters converted to lowercase. There's a caveat to this functionality, however: any characters with accents (circumflex, grave, tilde, umlaut, and all other accents on letters) won't be converted to lowercase. ucwords returns a string with the first character of each word capitalized, assuming that character is alphabetic. There's one more that we didn't show you in our code, but would be helpful to have in your back pocket: ucfirst, which performs the same as ucwords by making the first letter of every word an uppercase letter.
Checking for a String
To detect whether a string is part of another string, use strstr, shown in Figure. This function takes two parameters: the string to search through and the string to search for. It is not case sensitive; if you want to use a function that is case sensitive, use stristr. Lastly, there is strops, which finds the position of every first occurrence of the string you specified.
Detecting whether a string is contained in another string
Figure outputs the following:
Passwords cannot contain the word "password".
Sometimes it's useful to also know the position of a string that matches another string.
Using String Position and Substring to Extract a Portion of a String
We're going to use several string functions together. Let's take the string testing testing Username:Michele Davis and retrieve only the name. Figure shows how several functions can be used together to search and extract a portion of string.
Using several functions together to extract a portion of a string
Use strpos to search for Username: and return its position in the string with zero being the first position. Use strlen to add on to that position to find where you need to start extracting from the $test_string. To extract the name, use substr, which takes the string as a parameter, returning everything after the $position character in the string. Figure shows the end result of your labor.
Pulling the username out of a larger string
The number 16 in our example is the position of our username. If you look at the code, it says:
This is where the 16 comes from.
Next up, we'll introduce how to display and work with dates and times.