11.1. String FunctionsBecause 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. 11.1.1. Formatting Strings for DisplaySo 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. 11.1.1.1. Using printfThe 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 Example 11-1. Example 11-1. Displaying a number in binary format
This code then produces the output shown in Figure 11-1. Figure 11-1. Displaying 42 in binary formatThe formatting string in Example 11-1 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 Example 11-2. Example 11-2. printf puts the numbers into the string
When called from a web browser, the code in Example 11-2 displays Figure 11-2. Figure 11-2. Including two numbers in the stringSo far, the only type specifier we've used is b for binary, but there are more. Table 11-1 lists numeric type specifiers.
The last column of Table 11-1 was generated with the code in Example 11-3. Example 11-3. Displaying the same number in different formats
Example 11-3 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". 11.1.1.2. PaddingYou 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 Example 11-4. If the output of the parameter uses fewer spaces than the number you specify, zeros are filled in on the left. Example 11-4. Using left zero padding
Padding with zeros gives you the result shown in Figure 11-3. Figure 11-3. Zero padding to five spacesPadding with leading spaces, shown in Example 11-5, works the same way, except you specify a space after the percent sign instead of a zero. Example 11-5. Using left space padding
Using the left space padding displays the screen shown in Figure 11-4. Figure 11-4. Left padding doesn't show up correctlyAs you can see in Figure 11-4, 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 Example 11-6. Example 11-6. Adding the <pre> and </pre> tags so the spaces display
In Figure 11-5, we correctly see the spaces. Figure 11-5. The spaces show up nowIf you don't specify the character to pad, as happens in Example 11-7, printf assumes space padding and outputs a formatted string, like our example in Figure 11-5. Example 11-7. Left padding using the default of spaces
This code is equivalent to Example 11-5, and produces the same result, shown in Figure 11-6. Figure 11-6. Still left paddedTo right pad fields, simply put a negative number in the padding field, as in Example 11-8. Example 11-8. Right padding with spaces
And the output from the negative number in the padding field displays Figure 11-7. Figure 11-7. Padding on the right11.1.1.3. Specifying precisionSometimes 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: %.number_of_decimals_to_displayf Example 11-9 shows a value of 42.4242 set to display as currency. Example 11-9. Displaying a real number in money format
Our code displays with the dollar sign and decimal correctly, as shown in Figure 11-8. Figure 11-8. Only two decimal points displayEven if you replace the value of 42.4242 with 42, Example 11-9 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 11-9 breaks apart the conversion specifier %08.2f. Figure 11-9. The segments of a conversion specifierThe conversion specification in Figure 11-9 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. 11.1.1.4. Using sprintfThe sprintf function works exactly the same way as print, except its output is sent to a string. In Example 11-10, 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. Example 11-10. Using sprintf with a variable
Figure 11-10 displays the result. Figure 11-10. The output of the $total variableSometimes 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. 11.1.2. LengthThe 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. Example 11-11 shows how to use this. Example 11-11. Calculating the length of a string
Our password code above displays the screen in Figure 11-11. Figure 11-11. The password wasn't long enough to be secureWe'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. 11.1.3. Changing CasePHP 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. Example 11-12 uses each of them with the same string. Example 11-12. Using the word case functions
The code in Example 11-12 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. 11.1.4. Checking for a StringTo detect whether a string is part of another string, use strstr, shown in Example 11-13. 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. Example 11-13. Detecting whether a string is contained in another string
Example 11-13 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. 11.1.5. Using String Position and Substring to Extract a Portion of a StringWe're going to use several string functions together. Let's take the string testing testing Username:Michele Davis and retrieve only the name. Example 11-14 shows how several functions can be used together to search and extract a portion of string. Example 11-14. 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 11-12 shows the end result of your labor. Figure 11-12. Pulling the username out of a larger stringThe number 16 in our example is the position of our username. If you look at the code, it says: echo "$position<br>"; This is where the 16 comes from. Next up, we'll introduce how to display and work with dates and times. |