PHP String Functions
String functions are ready-made tools that measure and change text. Each one takes a string in and hands back a new value to print or store.
strlen counts characters
<?php
echo strlen("Hello"), "\n";Uppercase and lowercase
<?php
echo strtoupper("Hello"), "\n";
echo strtolower("Hello"), "\n";str_replace swaps a word
<?php
echo str_replace("world", "PHP", "Hello world"), "\n";strpos finds a word or fails
A missing word gives false instead of an index, and var_dump shows the difference plainly.
<?php
var_dump(strpos("Hello world", "world"));
var_dump(strpos("Hello world", "mars"));substr copies the tail
<?php
echo substr("Hello world", 6), "\n";Example
<?php
$email = "hana@example.com";
$at = strpos($email, "@");
echo substr($email, 0, $at), "\n";
echo substr($email, $at + 1), "\n";Key points
- A string function is a ready-made tool that works on text.
- strlen counts the characters in a string.
- strtoupper changes every letter in a string to uppercase.
- strtolower changes every letter in a string to lowercase.
- str_replace takes the text to find, the replacement text, and the string to change.
- strpos finds the starting index of a piece of text inside a string.
- substr copies out the part of a string that starts at a given index.
In this example, strpos finds the index of the @ sign in the email address. The first substr call copies from the start up to that index, which gives the user name. The second substr call starts one step past the @ sign and copies the rest, which gives the domain.
Note
The original string stays unchanged, because each function builds a new value.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does echo strtoupper("php"); print?