A Practical Cheat Sheet for PHP String Functions

PHP has an enormous standard library of string functions, inconsistent naming conventions and all — a working knowledge of the common ones saves constant trips to the documentation.

str_contains("Hello World", "World");       // true (PHP 8+)
str_starts_with("Hello", "He");              // true
str_pad("7", 3, "0", STR_PAD_LEFT);          // "007"
substr("Hello World", 0, 5);                 // "Hello"
str_replace("World", "PHP", "Hello World");  // "Hello PHP"
trim("  padded  ");                          // "padded"
explode(",", "a,b,c");                       // ['a', 'b', 'c']
implode(", ", ['a', 'b', 'c']);              // "a, b, c"
sprintf("%05.2f", 3.14159);                  // "03.14"
wordwrap("A long sentence here", 10, "\n", true);
ucwords("hello world");                      // "Hello World"

PHP 8’s str_contains(), str_starts_with(), and str_ends_with() replaced the old, error-prone pattern of checking strpos() !== false — worth updating older code to use them for readability alone.