String Functions
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.
Capitalization
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:
The result displayed is as follows:
$phrase = "I love PHP";
echo strtoupper($phrase) . "<br>";
echo strtolower($phrase) . "<br>";
If you wanted to functions capitalize only the first character of a string, you use ucfirst:
I LOVE PHP
i love php
You can also capitalize the first letter of each wordwhich is useful for namesby using ucwords:
$phrase = "welcome to the jungle";
echo $ucfirst($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:
$phrase = "green bay packers";
echo ucwords($phrase);
$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:
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:
$phrase = "I love PHP";
echo substr($phrase, 3, 5);
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, 2);
If you need to know how long a string is, you use the strlen function:
echo substr($phrase, -3);
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:
echo strlen($phrase);
$email = "chris@lightwood.net";
echo strpos($email, "@");
$domain = strstr($email, "@");
$domain = strstr($email, strpos($email, "@"));