String Functions
Quick reference for PHP's string functions. They work on bytes by default; for Unicode-aware versions use the mb_* family.
Length & case
| Function | Returns |
|---|---|
strlen($s) / mb_strlen($s) | Bytes / characters. |
strtolower / strtoupper / ucfirst / ucwords / mb_* | Case. |
lcfirst($s) | Lowercase first char. |
Trim & pad
| Function | Does |
|---|---|
trim / ltrim / rtrim | Strip whitespace (or chars you specify). |
str_pad($s, $len, $with, $where) | Pad to length. |
str_repeat($s, $n) | Repeat. |
Search & test
| Function | Returns |
|---|---|
str_contains($haystack, $needle) (8.0+) | True / false. |
str_starts_with / str_ends_with (8.0+) | Prefix / suffix. |
strpos / strrpos | Index, or false. |
substr_count($s, $needle) | Count occurrences. |
ctype_digit / ctype_alpha / ctype_alnum | Character-class checks. |
Modify
| Function | Returns |
|---|---|
substr($s, $start, $len) | Slice. |
str_replace($from, $to, $s) | Replace. |
strtr($s, $from, $to) | Translate chars / words. |
str_split($s, $len) | Split into N-sized pieces. |
explode($sep, $s) / implode($sep, $arr) | Split / join. |
wordwrap / nl2br | Line wrapping / convert \n to <br>. |
Format
| Function | Returns |
|---|---|
sprintf('%05d', 42) | Formatted string. |
number_format(1234.5, 2) | "1,234.50" |
htmlspecialchars($s) | Escape for HTML. |
urlencode / rawurlencode | Escape for URLs. |
bin2hex / hex2bin | Byte ↔ hex. |
base64_encode / decode | Base64. |
Tip: Use
mb_* functions whenever the input might contain non-ASCII. strlen('é') returns 2 (bytes); mb_strlen('é') returns 1 (character).Example
Example
<?php
$s = ' Hello, PHP! ';
echo trim($s), PHP_EOL;
echo strtoupper($s), PHP_EOL;
echo str_replace('PHP', 'world', $s), PHP_EOL;
print_r(explode(',', 'a,b,c'));
echo implode('-', ['a', 'b', 'c']);
Try it Yourself »
Exercise
Trim whitespace from both ends.
($s)
Four letters.
Discussion
Loading…