PHP Strings
In PHP, strings are sequences of characters used to store and manipulate text. PHP offers several ways to define and work with strings.
String Syntax in PHP
There are four primary ways to define strings in PHP:
-
Single-quoted strings (
'
)-
Simpler and faster
-
Variables and escape sequences (except
\\
and\'
) are not parsed
-
-
Double-quoted strings (
"
)-
Parses variables and escape sequences
-
-
Heredoc syntax (
<<<
)-
Acts like double quotes
-
-
Nowdoc syntax (
<<<'
)-
Acts like single quotes
-
Common String Functions
Function | Description |
---|---|
strlen($str) |
Returns the length of a string |
strtoupper($str) |
Converts to uppercase |
strtolower($str) |
Converts to lowercase |
strpos($haystack, $needle) |
Finds the position of the first occurrence |
substr($str, $start, $length) |
Extracts part of a string |
str_replace($search, $replace, $subject) |
Replaces all occurrences |
trim($str) |
Removes whitespace from both ends |
String Interpolation
Works in double-quoted and heredoc strings:
String Concatenation
Use the dot operator (.
):