Section 11.1. String Functions


11.1. String Functions

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:

  • Formatting strings for display

  • Calculating the length of a string

  • Changing a string's case to uppercase or lowercase

  • Searching for strings within strings and returning the position of the match

  • How to return just a portion of a string, which is a substring

We'll start with formatting strings, since that will help you throughout the rest of the topics.

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

11.1.1.1. Using printf

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 Example 11-1.

Example 11-1. Displaying a number in binary format

 <?php printf("The computer stores the number 42 internally as %b.",42); ?> 

This code then produces the output shown in Figure 11-1.

Figure 11-1. Displaying 42 in binary format


The 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

 <?php printf("The computer stores the numbers 42, and 256 internally as %b and %b.", 42,256); ?> 

When called from a web browser, the code in Example 11-2 displays Figure 11-2.

Figure 11-2. Including two numbers in the string


So far, the only type specifier we've used is b for binary, but there are more. Table 11-1 lists numeric type specifiers.

Table 11-1. Type specifiers for numbers

Specifier

Meaning

Example (using 42)

D

Display as a decimal number

42

B

Display as a binary number

101010

C

Display as ASCII equivalent

*

F

Display as a floating-point number, double precision

42.000000

O

Display as an octal number, base 8

52

S

Display as a string

42

X

Display as a lowercase hexadecimal

2a

X

Display as an uppercase hexadecimal

2A


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

 <?php $value=42; printf("%d<br>",$value); printf("%b<br>",$value); printf("%c<br>",$value); printf("%f<br>",$value); printf("%o<br>",$value); printf("%s<br>",$value); printf("%x<br>",$value); printf("%X<br>",$value); ?> 

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

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

 <?php printf("Zero padding can help alignment %05d.", 42); ?> 

Padding with zeros gives you the result shown in Figure 11-3.

Figure 11-3. Zero padding to five spaces


Padding 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

 <?php printf("Space padding can be tricky in HTML % 5d.", 42); ?> 

Using the left space padding displays the screen shown in Figure 11-4.

Figure 11-4. Left padding doesn't show up correctly


As 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

 <?php printf("<pre>Space padding can be tricky in HTML % 5d.</pre>", 42); ?> 

In Figure 11-5, we correctly see the spaces.

Figure 11-5. The spaces show up now


If 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

 <?php printf("<pre>Space padding can be tricky in HTML %5d.</pre>", 42); ?> 

This code is equivalent to Example 11-5, and produces the same result, shown in Figure 11-6.

Figure 11-6. Still left padded


To right pad fields, simply put a negative number in the padding field, as in Example 11-8.

Example 11-8. Right padding with spaces

 <?php printf("<pre>Space padding can be tricky in HTML %-5d.</pre>", 42); ?> 

And the output from the negative number in the padding field displays Figure 11-7.

Figure 11-7. Padding on the right


11.1.1.3. Specifying precision

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:

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

 <?php printf("Please pay $%.2f. ", 42.4242); ?> 

Our code displays with the dollar sign and decimal correctly, as shown in Figure 11-8.

Figure 11-8. Only two decimal points display


Even 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 specifier


The 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 sprintf

The 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

 <?php $total=sprintf("Please pay $%.2f. ", 42.4242); echo $total; ?> 

Figure 11-10 displays the result.

Figure 11-10. 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.

11.1.2. Length

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. Example 11-11 shows how to use this.

Example 11-11. Calculating the length of a string

 <?php   $password="secret1";   if (strlen($password) <= 5)   {     echo("Passwords must be a least 5 characters long.");   }   else {     echo ("Password accepted.");   } ?> 

Our password code above displays the screen in Figure 11-11.

Figure 11-11. 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.

11.1.3. Changing Case

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. Example 11-12 uses each of them with the same string.

Example 11-12. Using the word case functions

 <?php   $username="John Doe";   echo("$username in upper case is ".strtoupper($username).".<br>");   echo("$username in lower case is ".strtolower($username).".<br>");   echo("$username in first letter upper case is ".ucwords($username).".<br>"); ?> 

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 String

To 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

 <?php   $password="secretpassword1";   if (strstr($password,"password")){     echo('Passwords cannot contain the word "password".');   }   else {     echo ("Password accepted.");   } ?> 

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

 <?php   $test_string="testing testing Username:Michele Davis";   $position=strpos($test_string,"Username:");   //add on the length of the Username:   $start=$position+strlen("Username:");   echo "$test_string<br>";   echo "$position<br>";   echo substr($test_string,$start); ?> 

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 string


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



Learning PHP and MySQL
Learning PHP and MySQL
ISBN: 0596101104
EAN: 2147483647
Year: N/A
Pages: 135

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net