4.7. Manipulating and Searching StringsPHP has many functions to work with strings. The most commonly used functions for searching and modifying strings are those that use regular expressions to describe the string in question. The functions described in this section do not use regular expressionsthey are faster than regular expressions, but they work only when you're looking for a fixed string (for instance, if you're looking for "12/11/01" rather than "any numbers separated by slashes"). 4.7.1. SubstringsIf you know where the data that you are interested in lies in a larger string, you can copy it out with the substr( ) function:
The start argument is the position in string at which to begin copying, with 0 meaning the start of the string. The length argument is the number of characters to copy (the default is to copy until the end of the string). For example:
To learn how many times a smaller string occurs in a larger one, use substr_count( ):
For example:
The substr_replace( ) function permits many kinds of string modifications:
The function replaces the part of original indicated by the start (0 means the start of the string) and length values with the string new. If no fourth argument is given, substr_replace( ) removes the text from start to the end of the string. For instance:
Use a length of 0 to insert without deleting:
Use a replacement of "" to delete without inserting:
Here's how you can insert at the beginning of the string:
A negative value for start indicates the number of characters from the end of the string from which to start the replacement:
A negative length indicates the number of characters from the end of the string at which to stop deleting:
4.7.2. Miscellaneous String FunctionsThe strrev( ) function takes a string and returns a reversed copy of it:
For example:
The str_repeat( ) function takes a string and a count and returns a new string consisting of the argument string repeated count times:
For example, to build a crude horizontal rule:
The str_pad( ) function pads one string with another. Optionally, you can say what string to pad with, and whether to pad on the left, right, or both:
The default is to pad on the right with spaces:
The optional third argument is the string to pad with:
The optional fourth argument can be either STR_PAD_RIGHT (the default), STR_PAD_LEFT, or STR_PAD_BOTH (to center). For example:
4.7.3. Decomposing a StringPHP provides several functions to let you break a string into smaller components. In increasing order of complexity, they are explode( ), strtok( ), and sscanf( ). 4.7.3.1. Exploding and implodingData often arrives as strings, which must be broken down into an array of values. For instance, you might want to separate out the comma-separated fields from a string such as "Fred,25,Wilma." In these situations, use the explode( ) function:
The first argument, separator, is a string containing the field separator. The second argument, string, is the string to split. The optional third argument, limit, is the maximum number of values to return in the array. If the limit is reached, the last element of the array contains the remainder of the string:
The implode( ) function does the exact opposite of explode( )it creates a large string from an array of smaller strings:
The first argument, separator, is the string to put between the elements of the second argument, array. To reconstruct the simple comma-separated value string, simply say:
The join( ) function is an alias for implode( ). 4.7.3.2. TokenizingThe strtok( ) function lets you iterate through a string, getting a new chunk (token) each time. The first time you call it, you need to pass two arguments: the string to iterate over and the token separator:
To retrieve the rest of the tokens, repeatedly call strtok( ) with only the separator:
For instance, consider this invocation:
The strtok( ) function returns false when there are no more tokens to be returned. Call strtok( ) with two arguments to reinitialize the iterator. This restarts the tokenizer from the start of the string. 4.7.3.3. sscanf( )The sscanf( ) function decomposes a string according to a printf( )-like template:
If used without the optional variables, sscanf( ) returns an array of fields:
Pass references to variables to have the fields stored in those variables. The number of fields assigned is returned:
4.7.4. String-Searching FunctionsSeveral functions find a string or character within a larger string. They come in three families: strpos( ) and strrpos( ), which return a position; strstr( ), strchr( ), and friends, which return the string they find; and strspn( ) and strcspn( ), which return how much of the start of the string matches a mask. In all cases, if you specify a number as the "string" to search for, PHP treats that number as the ordinal value of the character to search for. Thus, these function calls are identical because 44 is the ASCII value of the comma:
All the string-searching functions return false if they can't find the substring you specified. If the substring occurs at the beginning of the string, the functions return 0. Because false casts to the number 0, always compare the return value with === when testing for failure:
4.7.4.1. Searches returning positionThe strpos( ) function finds the first occurrence of a small string in a larger string:
If the small string isn't found, strpos( ) returns false. The strrpos( ) function finds the last occurrence of a character in a string. It takes the same arguments and returns the same type of value as strpos( ). For instance:
If you pass a string as the second argument to strrpos( ), only the first character is searched for. To find the last occurrence of a multicharacter string, reverse the strings and use strpos( ):
4.7.4.2. Searches returning rest of stringThe strstr( ) function finds the first occurrence of a small string in a larger string and returns from that small string on. For instance:
The variations on strstr( ) are:
As with strrpos( ), strrchr( ) searches backward in the string, but only for a character, not for an entire string. 4.7.4.3. Searches using masksIf you thought strrchr( ) was esoteric, you haven't seen anything yet. The strspn( ) and strcspn( ) functions tell you how many characters at the beginning of a string are comprised of certain characters:
For example, this function tests whether a string holds an octal number:
The c in strcspn( ) stands for complementit tells you how much of the start of the string is not composed of the characters in the character set. Use it when the number of interesting characters is greater than the number of uninteresting characters. For example, this function tests whether a string has any NUL-bytes, tabs, or carriage returns:
4.7.4.4. Decomposing URLsThe parse_url( ) function returns an array of components of a URL:
For example:
The possible keys of the hash are scheme, host, port, user, pass, path, query, and fragment. |
Monday, October 19, 2009
Section 4.7. Manipulating and Searching Strings
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment