String Functions
PHPPHP has over 100 built-in string functions. Here are the most important ones you'll use in everyday PHP and Laravel development.
String Length & Case
PHP
<?php
$str = "Hello, World!";
echo strlen($str); // 13 — length
echo strtolower($str); // hello, world!
echo strtoupper($str); // HELLO, WORLD!
echo ucfirst("hello"); // Hello
echo ucwords("hello world"); // Hello World
echo str_word_count($str); // 2 — word count
?>Search & Replace
PHP
<?php
$str = "Hello, World!";
// Find position
echo strpos($str, "World"); // 7 — position of "World"
echo strrpos($str, "l"); // 10 — last position of "l"
// Check if contains
echo str_contains($str, "World"); // true (PHP 8)
echo str_starts_with($str, "Hello"); // true (PHP 8)
echo str_ends_with($str, "!"); // true (PHP 8)
// Replace
echo str_replace("World", "PHP", $str); // Hello, PHP!
echo str_ireplace("hello", "Hi", $str); // Hi, World! (case-insensitive)
?>Substring
PHP
<?php
$str = "Hello, World!";
echo substr($str, 7); // World! — from position 7
echo substr($str, 7, 5); // World — 5 chars from position 7
echo substr($str, -6); // World! — last 6 chars
// Trim whitespace
$padded = " Hello ";
echo trim($padded); // "Hello"
echo ltrim($padded); // "Hello " (left trim)
echo rtrim($padded); // " Hello" (right trim)
?>Split & Join
PHP
<?php
// Split string into array
$csv = "apple,banana,cherry";
$fruits = explode(",", $csv);
// ["apple", "banana", "cherry"]
// Join array into string
$joined = implode(" | ", $fruits);
// "apple | banana | cherry"
// Split into characters
$chars = str_split("Hello", 1);
// ["H", "e", "l", "l", "o"]
?>Formatting
PHP
<?php
// sprintf — format a string
$name = "John";
$age = 25;
$message = sprintf("My name is %s and I am %d years old.", $name, $age);
echo $message; // My name is John and I am 25 years old.
// number_format — format numbers
echo number_format(1234567.891, 2); // 1,234,567.89
echo number_format(1234567.891, 2, '.', ','); // 1,234,567.89
// Padding
echo str_pad("5", 3, "0", STR_PAD_LEFT); // 005
?>💡
Laravel has a Str helper class with even more powerful string methods:
Str::slug(), Str::limit(), Str::camel(), Str::snake() and many more.Test your knowledge!
Take the PHP Basics quiz.