PHP String Functions

PHP String Functions

PHP has over 100 built-in string functions. Here are the ones you will reach for every day.

1 - Length, Case, Trim

$str = "  Hello, World!  ";

strlen($str);          // 18
strtoupper($str);      // "  HELLO, WORLD!  "
strtolower($str);      // "  hello, world!  "
ucfirst("hello");      // "Hello"
ucwords("hello world"); // "Hello World"
trim($str);            // "Hello, World!"
ltrim($str);           // "Hello, World!  "
rtrim($str);           // "  Hello, World!"

2 - Searching

$str = "I love PHP programming";

strpos($str, "PHP");         // 7
strrpos($str, "p");          // 17 (last occurrence)
str_contains($str, "PHP");   // true  (PHP 8)
str_starts_with($str, "I");  // true  (PHP 8)
str_ends_with($str, "ing");  // true  (PHP 8)

3 - Replacing and Splitting

str_replace("PHP", "Laravel", $str);
// "I love Laravel programming"

$parts  = explode(" ", $str);    // split to array
$joined = implode("-", $parts);  // join with separator

substr($str, 7, 3); // "PHP"

4 - Formatting

sprintf("Hello, %s! You are %d years old.", "Alice", 30);
str_pad("5", 3, "0", STR_PAD_LEFT); // "005"
str_repeat("ab", 3);                // "ababab"
wordwrap($longText, 80, "\n", true); // wrap at 80 chars

Note: For Unicode strings, use the mb_* family: mb_strlen(), mb_strtoupper(), mb_substr(). The standard functions count bytes, not characters, and will corrupt multi-byte UTF-8 strings.

-Tip-