Let's take a look at some of the other string functions available in PHP. The full list of string functions can be found in the online manual, at www.php.net/manual/en/ref.strings.php.
You can switch the capitalization of a string to all uppercase or all lowercase by using strtoupper or strtolower, respectively.
The following example demonstrates the effect this has on a mixed-case string:
$phrase = "I love PHP"; echo strtoupper($phrase) . "<br>"; echo strtolower($phrase) . "<br>";
The result displayed is as follows:
I LOVE PHP i love php
If you wanted to functions capitalize only the first character of a string, you use ucfirst:
$phrase = "welcome to the jungle"; echo $ucfirst($phrase);
You can also capitalize the first letter of each wordwhich is useful for namesby using ucwords:
$phrase = "green bay packers"; echo ucwords($phrase);
Neither ucfirst nor ucwords affects characters in the string that are already in uppercase, so if you want to make sure that all the other characters are lowercase, you must combine these functions with strtolower, as in the following example:
$name = "CHRIS NEWMAN"; echo ucwords(strtolower($name));
Dissecting a String
The substr function allows you to extract a substring by specifying a start position within the string and a length argument. The following example shows this in action:
$phrase = "I love PHP"; echo substr($phrase, 3, 5);
This call to substr returns the portion of $phrase from position 3 with a length of 5 characters. Note that the position value begins at zero, not one, so the actual substring displayed is ove P.
If the length argument is omitted, the value returned is the substring from the position given to the end of the string. The following statement produces love PHP for $phrase:
echo substr($phrase, 2);
If the position argument is negative, substr counts from the end of the string. For example, the following statement displays the last three characters of the stringin this case, PHP:
echo substr($phrase, -3);
If you need to know how long a string is, you use the strlen function:
To find the position of a character or a string within another string, you can use strpos. The first argument is often known as the haystack, and the second as the needle, to indicate their relationship.
The following example displays the position of the @ character in an email address:
$email = "email@example.com"; echo strpos($email, "@");
The strstr function extracts a portion of a string from the position at which a character or string appears up to the end of the string. This is a convenience function that saves your using a combination of strpos and substr.
The following two statements are equivalent:
$domain = strstr($email, "@"); $domain = strstr($email, strpos($email, "@"));