iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

FunctionReturns
strlen($s) / mb_strlen($s)Bytes / characters.
strtolower / strtoupper / ucfirst / ucwords / mb_*Case.
lcfirst($s)Lowercase first char.

Trim & pad

FunctionDoes
trim / ltrim / rtrimStrip whitespace (or chars you specify).
str_pad($s, $len, $with, $where)Pad to length.
str_repeat($s, $n)Repeat.

Search & test

FunctionReturns
str_contains($haystack, $needle) (8.0+)True / false.
str_starts_with / str_ends_with (8.0+)Prefix / suffix.
strpos / strrposIndex, or false.
substr_count($s, $needle)Count occurrences.
ctype_digit / ctype_alpha / ctype_alnumCharacter-class checks.

Modify

FunctionReturns
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 / nl2brLine wrapping / convert \n to <br>.

Format

FunctionReturns
sprintf('%05d', 42)Formatted string.
number_format(1234.5, 2)"1,234.50"
htmlspecialchars($s)Escape for HTML.
urlencode / rawurlencodeEscape for URLs.
bin2hex / hex2binByte ↔ hex.
base64_encode / decodeBase64.
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)

Test yourself

Q1. For UTF-8 length use…
Q2. str_contains arrived in…
Q3. For HTML-safe output use…

Discussion

Loading…