- Listing of String Functions
- Using the String Functions
- Formatting Strings
- Converting to and from Strings
- Creating Arrays
- Modifying Arrays
- Removing Array Elements
- Looping Over Arrays
- Listing of the Array Functions
- Sorting Arrays
- Navigating through Arrays
- Imploding and Exploding Arrays
- Extracting Variables from Arrays
- Merging and Splitting Arrays
- Comparing Arrays
- Manipulating the Data in Arrays
- Creating Multidimensional Arrays
- Looping Over Multidimensional Arrays
- Using the Array Operators
- Summary
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 table—and 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};