Using the String Functions


Here's an example that puts some of the useful string functions to work:

 <?php     echo trim("    No worries."), "\n";     echo substr("No worries.", 3, 7), "\n";     echo "\"worries\" starts at position ", strpos("No worries.", "worries"), "\n";     echo ucfirst("no worries."), "\n";     echo "\"No worries.\" is ", strlen("No worries."), " characters long.\n";     echo substr_replace("No worries.", "problems.", 3, 8), "\n";     echo chr(65), chr(66), chr(67), "\n";     echo strtoupper("No worries."), "\n"; ?> 

In this example, we're using trim to trim leading spaces from a string, substr to extract a substring from a string, strpos to search a string for a substring, ucfirst to convert the first character of a string to uppercase, strlen to determine a string's length, substr_replace to replace a substring with another string, chr to convert an ASCII code to a letter (ASCII 65 = "A", ASCII 66 = "B", and so on), and strtoupper to convert a string to uppercase.

Here are the results of this script, line by line:

 No worries. worries "worries" starts at position 3 No worries. "No worries." is 11 characters long. No problems. ABC NO WORRIES. 

This example shows some of the more powerful string functions at work. The list of string functions is a long one, but you'll usually find what you need in the tableand if not, you can often cobble together a solution using two or more of these functions.

Here's another tip: In PHP, you can also pick out the characters in a string by enclosing the place of the character you want in curly braces, like this:

 $string = 'No worries.'; $first_character = $string{0}; 



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

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