Home > Articles > Programming > PHP

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Using the String Functions

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

    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" starts at position 3
No worries.
"No worries." is 11 characters long.
No problems.

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};
  • + Share This
  • 🔖 Save To Your Account