If you're looking to perform a little cosmetic surgery on your strings, a good place to start is the family of trim() functions. The most useful of these, trim(), is constructed specifically to remove whitespace from the beginning and end of a string. This comes in handy if you need to remove whitespace from a value prior to using it elsewhere (a database insert, maybe?) It's also a good idea to use the trim() function on data entered into online forms, in order to ensure that your error-checking routines don't miss entries containing only whitespace. Here's an example which illustrates what I mean: You can also use the ltrim() and rtrim() functions, which remove whitespace from the beginning and end of a string respectively. The next few string functions come in very handy when adjusting the case of a text string from lower- to upper-case, or vice-versa: strtolower() - convert string to lower case strtoupper()- convert string to upper case ucfirst() - convert the first character of string to upper case ucwords() - convert the first character of each word in string to upper case Here's an example: You've already used the print() function extensively to display output. However, the print() function doesn't allow you to format output in any significant manner - for example, you can't write 1000 as 1,000 or 1 as 00001. And so the clever PHP developers came up with the sprintf() function, which allows you to define the format in which data is output. Consider the following example: As you might imagine, that's not very friendly. Ideally, you'd like to display just the "significant digits" of the result. And so, you'd use the sprintf() function: A quick word of explanation here: the PHP sprintf() function is very similar to the printf() function that C programmers are used to. In order to format the output, you need to use "field templates", templates which represent the format you'd like to display. Some common field templates are: %s string %d decimal number %x hexadecimal number %o octal number %f float number You can also combine these field templates with numbers which indicate the number of digits to display - for example, %1.2f implies that PHP should only display two digits after the decimal point. If you'd like the formatted string to have a minimum length, you can tell PHP which character to use for padding by prefixing it with a single quote ('). Here are a few more examples of sprintf() in action: In addition to the sprintf() function, PHP also offers the strpad() function, which is used for padding strings to a specific length. This function accepts a string or string variable as argument, together with the minimum string length required; a couple of optional arguments allow you to also specify which character to use for padding, and the direction in which padding is to take place. Here are a couple of examples: Finally, the wordwrap() function can be used to break long sentences at a specified length.
blog comments powered by Disqus |