Getting Started
Working with Strings
Master PHP string functions for manipulation, searching, formatting, and regular expressions.
String Basics
PHP strings can be declared with single quotes '' or double quotes "".
- Single quotes: No variable interpolation, faster for plain strings
- Double quotes: Variables and escape sequences are parsed
Heredoc and Nowdoc
For multi-line strings, use heredoc (with interpolation) or nowdoc (without).
Common String Functions
PHP has a rich library of string manipulation functions. Key ones include:
strlen, strtolower, strtoupper, trim, str_replace, strpos, substr, explode, implode
Example
php
<?php
$name = "Alice";
$age = 30;
// Double quotes - interpolation works
echo "Hello, $name! You are $age years old.";
// Single quotes - no interpolation
echo 'Hello, $name!'; // literal: Hello, $name!
// String length
$str = "Hello, World!";
echo strlen($str); // 13
// Case functions
echo strtolower("HELLO"); // hello
echo strtoupper("hello"); // HELLO
echo ucfirst("hello world"); // Hello world
echo ucwords("hello world"); // Hello World
// Trimming
$padded = " hello ";
echo trim($padded); // "hello"
echo ltrim($padded); // "hello "
echo rtrim($padded); // " hello"
// Find and replace
$text = "Hello, World!";
echo str_replace("World", "PHP", $text); // Hello, PHP!
// Find position
echo strpos("Hello World", "World"); // 6
echo strpos("Hello World", "xyz"); // false
// Substring
echo substr("Hello World", 6); // World
echo substr("Hello World", 0, 5); // Hello
// Split and join
$csv = "apple,banana,cherry";
$fruits = explode(",", $csv); // array
$joined = implode(" | ", $fruits); // apple | banana | cherry
// String padding
echo str_pad("42", 5, "0", STR_PAD_LEFT); // 00042
// Heredoc
$message = <<<EOT
Hello, $name!
Your age is $age.
EOT;
echo $message;Try it yourself — PHP