Strings in PHP
? Strings in PHP
Strings are sequences of characters and are one of the most commonly used data types in PHP. They can be enclosed in single quotes (') or double quotes ("), and PHP provides many functions to manipulate them.
? Creating Strings
$str1 = 'Hello World'; // Single-quoted$str2 = "Hello World"; // Double-quoted? Key Difference:
Single quotes: No variable parsing, no escape sequences (except
\\and\')Double quotes: Parses variables and escape sequences
$name = "Alice";echo 'Hello $name'; // Output: Hello $nameecho "Hello $name"; // Output: Hello Alice? String Concatenation
Use the . operator to combine strings:
$first = "Hello";$second = "World";echo $first . " " . $second; // Output: Hello World? Common String Functions
| Function | Description |
|---|---|
strlen($str) | Length of string |
strtolower($str) | Convert to lowercase |
strtoupper($str) | Convert to uppercase |
ucfirst($str) | Uppercase first letter |
lcfirst($str) | Lowercase first letter |
ucwords($str) | Capitalize words |
trim($str) | Remove whitespace from both ends |
ltrim($str) / rtrim($str) | Remove whitespace from left/right |
str_replace($search, $replace, $str) | Replace text |
strpos($haystack, $needle) | Find position of first occurrence |
substr($str, $start, $length) | Get part of string |
explode($delimiter, $str) | Split string into array |
implode($glue, $array) | Join array into string |
strrev($str) | Reverse a string |
? Example: Basic String Operations
$text = " Hello World! ";echo strlen($text); // 15echo trim($text); // Hello World!echo strtoupper($text); // HELLO WORLD! echo str_replace("World", "PHP", $text); // Hello PHP! ? Multiline Strings
1. Heredoc Syntax
$name = "Alice";$text = <<<EODHello $name,Welcome to PHP!EOD;echo $text;2. Nowdoc Syntax (like single quotes, no variable parsing)
$text = <<<'EOD'Hello $name,This is a raw string.EOD;