String Functions
Built-in tools to measure, change and search text.
What you will learn
- Use common string functions
Built-in string tools
PHP comes with many ready-made functions for working with text (a *string*). You do not have to write these yourself — just call them by name and hand them your text. Here are the ones you will reach for most:
| Function | Does |
|---|---|
strlen($s) | Length |
strtoupper($s) / strtolower($s) | Change case |
trim($s) | Remove surrounding spaces |
str_replace("a","b",$s) | Replace text |
substr($s, 0, 3) | Cut out part |
explode(",", $s) | Split into an array |
You can also chain functions — feed the result of one straight into another. This example first trims the spaces off some messy text, then changes the case or measures the length of the cleaned-up result:
<?php
$text = " CodingClave ";
echo strtoupper(trim($text)); // CODINGCLAVE
echo strlen(trim($text)); // 11
?>Read the calls from the inside out. trim($text) runs first and removes the leading and trailing spaces, leaving "CodingClave". That clean text is then passed to strtoupper(...), which makes it all capitals, and on the next line to strlen(...), which counts its 11 letters.
Note: Output (in the browser):
CODINGCLAVE11
The two results print side by side: the upper-cased word, then its length. Note strlen counts the trimmed text (11), not the original with spaces — because trim ran first.
Q. Which function removes spaces from the start and end of a string?
✍️ Practice
- Clean and uppercase a messy string.
- Split "a,b,c" into an array with explode.
🏠 Homework
- Write a function that returns the initials from a full name.