With the basics out of the way, let's now turn to some of the other string functions available in PHP. Other than echo() and print(), the three functions you're likely to encounter most often are strlen(), explode() and implode(). The strlen() function returns the length of a particular string, and can come in handy for operations which involve processing every character in a string. The explode() function splits a string into smaller components on the basis of a user-specified pattern, and then returns these elements as an array. This function is particularly handy if you need to take a string containing a list of items (for example, a comma-delimited list) and separate each element of the list for further processing. Here's an example: Obviously, you can also do the reverse - the implode() function creates a single string from all the elements of an array, joining them together with a user-defined separator. Reversing the example above, we have: The chr() and ord() functions come in handy when converting from ASCII codes to characters and vice-versa. For example, In case you need to repeat a string, PHP offers the str_repeat() function, which accepts two arguments - the string to be repeated, and the number of times to repeat it. Here's an example: And if you ever find the need to reverse a string, well, you can always reach for the strrev() function... I couldn't have put it better myself!{mospagebreak title=Of Jumping Cows And Purple Pumpkins} Next up, the substr() function. As the name implies, this is the function that allows you to slice and dice strings into smaller strings. Here's what it looks like: where "string" is a string or string variable, "start" is the position to begin slicing at, and "length" is the number of characters to return from "start". Here's an example which demonstrates how this works: You can use this function to split a string into smaller chunks of a fixed size, or you could take the easy way out and use the built-in chunk_split() function, designed specifically for this purpose. You can also use the substr() function to extract a particular character from a string, or you can use one of PHP4's cool new features and access a character by specifying its position in the string within curly braces (remember that the first character equates to position 0).
blog comments powered by Disqus |