Log in Sign up

Length and case

FunctionExampleResult
strlen($s)strlen("Hallo")5 (counts bytes)
mb_strlen($s)mb_strlen("Größe")5 (counts characters)
strtolower / strtoupperstrtoupper("abc")ABC
mb_strtolower / mb_strtoupperfor UTF-8 text like ä, ö, ü
ucfirst / lcfirstucfirst("hello")Hello
ucwordsucwords("hello world")Hello World

For text with umlauts or other non-ASCII characters, use the mb_ versions.

Trimming and padding

FunctionExampleResult
trim / ltrim / rtrimtrim(" hi ")hi
trim("/path/", "/")path
str_padstr_pad("7", 3, "0", STR_PAD_LEFT)007
str_repeatstr_repeat("-", 5)-----

Searching

FunctionReturns
str_contains($s, "x")bool (PHP 8)
str_starts_with($s, "x") / str_ends_withbool (PHP 8)
strpos($s, "x")position or false
striposlike strpos, case-insensitive
strrposlast position
substr_count($s, "x")number of occurrences
if (strpos($s, "a") !== false) { ... }  // !== matters: position 0 is falsy

Extracting and replacing

FunctionExampleResult
substr($s, start, length)substr("Bugfish", 0, 3)Bug
substr("Bugfish", -4)fish
mb_substrUTF-8 safe version
str_replace(search, replace, $s)str_replace("a", "o", "bag")bog
str_ireplacecase-insensitive
substr_replacereplace part at a position
strrevstrrev("abc")cba
wordwrap($s, 40, "\n", true)wrap long text

Splitting and joining

$parts = explode(",", "a,b,c");      // ["a", "b", "c"]
$text  = implode(", ", $parts);      // "a, b, c"
$chars = str_split("abc");           // ["a", "b", "c"]
$lines = preg_split('/\R/', $text);  // split on any line break

Formatting

sprintf("%s has %d items costing %.2f €", "Anna", 3, 9.5);
// Anna has 3 items costing 9.50 €

sprintf("%05d", 42);                       // 00042
number_format(1234567.891, 2, ',', '.');   // 1.234.567,89
nl2br("line1\nline2");                     // inserts <br />
PlaceholderMeaning
%sstring
%dinteger
%f / %.2ffloat / with 2 decimals
%x / %bhex / binary
%%literal %

HTML and safety

FunctionPurpose
htmlspecialchars($s, ENT_QUOTES, 'UTF-8')escape < > & " ' – use for every user value printed to HTML
strip_tags($s)remove HTML tags
addslashesescape quotes (do not use for SQL – use PDO, see PHP Databases with PDO)
urlencode / rawurlencodeencode for URLs
base64_encode / base64_decodeBase64
md5, sha1, hash('sha256', $s)hashes (never for passwords)

Regular expressions (PCRE)

preg_match('/^\d{4}-\d{2}-\d{2}$/', $date);           // 1 if it matches, else 0
preg_match('/(\d+) items/', $s, $m);  echo $m[1];      // captured group
preg_match_all('/\d+/', "a1 b22 c333", $m);            // $m[0] = ["1","22","333"]
preg_replace('/\s+/', ' ', $s);                        // collapse whitespace
preg_quote($userInput, '/');                           // escape user text for a pattern

Add the u modifier (/.../u) when working with UTF-8.

Heredoc and nowdoc

$html = <<<HTML
    <h1>{$title}</h1>
    <p>$text</p>
    HTML;            // variables are inserted

$raw = <<<'TXT'
    $notAVariable
    TXT;             // nowdoc: printed literally

Previous: PHP Control Structures and Functions · Next: PHP Array Functions

Put together with AI as a quick reference I keep for my own work. Entries like this are usually not reviewed in detail by a person.