PHP Strings
A string is a sequence of characters. PHP provides four ways to create strings and a large library of built-in string functions.
Creating Strings
Single quotes treat everything literally. Double quotes parse variables and escape sequences. Heredoc and Nowdoc are used for multi-line strings.
<?php
$name = "Alice";
// Single quotes — literal
echo 'Hello $name'; // Hello $name
// Double quotes — parses variables
echo "Hello $name"; // Hello Alice
echo "Tab:\there"; // Tab: here
// Heredoc — like double quotes, multi-line
$text = <<<EOT
Hello $name,
Welcome to PHP!
EOT;
echo $text;
// Nowdoc — like single quotes, multi-line
$raw = <<<'EOT'
Hello $name,
No variable parsing here.
EOT;
echo $raw;
?>
Common String Functions
PHP has over 100 string functions. Here are the most frequently used ones.
<?php
$str = " Hello, World! ";
echo strlen($str); // 18 (includes spaces)
echo strtoupper($str); // " HELLO, WORLD! "
echo strtolower($str); // " hello, world! "
echo trim($str); // "Hello, World!"
echo ltrim($str); // "Hello, World! "
echo rtrim($str); // " Hello, World!"
$clean = trim($str);
echo str_replace("World", "PHP", $clean); // Hello, PHP!
echo strpos($clean, "World"); // 7
echo substr($clean, 7, 5); // World
echo str_repeat("ab", 3); // ababab
echo str_word_count($clean); // 2
echo ucfirst("hello world"); // Hello world
echo ucwords("hello world"); // Hello World
echo strrev("PHP"); // PHP reversed: PHP
?>
<?php
// explode / implode
$csv = "apple,banana,cherry";
$fruits = explode(",", $csv);
print_r($fruits); // Array ( [0] => apple [1] => banana [2] => cherry )
$joined = implode(" | ", $fruits);
echo $joined; // apple | banana | cherry
// sprintf — formatted string
$price = 9.5;
echo sprintf("Price: $%.2f", $price); // Price: $9.50
// number_format
echo number_format(1234567.891, 2, '.', ','); // 1,234,567.89
// String padding
echo str_pad("5", 3, "0", STR_PAD_LEFT); // 005
// Check if substring exists (PHP 8)
echo str_contains("Hello World", "World") ? "found" : "not found"; // found
echo str_starts_with("Hello", "He") ? "yes" : "no"; // yes
echo str_ends_with("Hello", "lo") ? "yes" : "no"; // yes
?>
Ready to Level Up Your Skills?
Explore 500+ free tutorials across 20+ languages and frameworks.