Strings in php
A string is a sequence of characters. In php, strings can be written inside single quotes, double quotes, heredoc, or nowdoc syntax.
Creating Stringsโ
<?php
$single = 'Hello World'; // Single quotes
$double = "Hello World"; // Double quotes
$name = "Alice";
$msg = "Hello, $name!"; // Variable interpolation (double only)
echo $msg; // Hello, Alice!
?>
String Lengthโ
<?php
echo strlen("Hello World"); // 11
?>
Heredoc Syntaxโ
Useful for multi-line strings with variable interpolation:
<?php
$name = "Alice";
$text = <<<EOT
Hello, $name!
Welcome to php.
EOT;
echo $text;
?>
Nowdoc Syntaxโ
Like heredoc but no variable interpolation (like single quotes):
<?php
$name = "Alice";
$text = <<<'EOT'
Hello, $name!
This will NOT be interpolated.
EOT;
echo $text; // Hello, $name!
?>
String Functionsโ
Case Manipulationโ
<?php
echo strtolower("HELLO"); // hello
echo strtoupper("hello"); // HELLO
echo ucfirst("hello world"); // Hello world
echo ucwords("hello world"); // Hello World
?>
Trimmingโ
<?php
echo trim(" Hello "); // "Hello"
echo ltrim(" Hello "); // "Hello "
echo rtrim(" Hello "); // " Hello"
?>
Searchingโ
<?php
$str = "Hello World";
echo strpos($str, "World"); // 6 (position)
echo strrpos($str, "l"); // 9 (last occurrence)
echo str_contains($str, "World"); // true (php 8+)
echo str_starts_with($str, "Hello"); // true (php 8+)
echo str_ends_with($str, "World"); // true (php 8+)
?>
Replacingโ
<?php
echo str_replace("World", "php", "Hello World"); // Hello php
// Case-insensitive replace
echo str_ireplace("WORLD", "php", "Hello World"); // Hello php
?>
Substringโ
<?php
$str = "Hello World";
echo substr($str, 6); // World
echo substr($str, 0, 5); // Hello
echo substr($str, -5); // World
?>
Splitting and Joiningโ
<?php
// Split string into array
$parts = explode(",", "Apple,Banana,Cherry");
print_r($parts); // ["Apple", "Banana", "Cherry"]
// Join array into string
$joined = implode(" - ", $parts);
echo $joined; // Apple - Banana - Cherry
?>
String Formattingโ
<?php
$name = "Alice";
$age = 30;
// sprintf
$msg = sprintf("Name: %s, Age: %d", $name, $age);
echo $msg; // Name: Alice, Age: 30
// number_format
echo number_format(1234567.891, 2); // 1,234,567.89
?>
Repeating Stringsโ
<?php
echo str_repeat("Ha", 3); // HaHaHa
?>
Reversing Stringsโ
<?php
echo strrev("Hello"); // olleH
?>
Padding Stringsโ
<?php
echo str_pad("5", 3, "0", STR_PAD_LEFT); // 005
echo str_pad("Hi", 10, "-", STR_PAD_BOTH); // ----Hi----
?>
Word Countโ
<?php
echo str_word_count("Hello World php"); // 3
?>
Note: In php, string indexes start at 0. Use $str[0] to access the first character of a string.
Finished reading? Mark this topic as complete.