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:

  1. Single-quoted strings (')

    • Simpler and faster

    • Variables and escape sequences (except \\ and \') are not parsed

    $name = 'John'; echo 'Hello, $name'; // Output: Hello, $name
  2. Double-quoted strings (")

    • Parses variables and escape sequences

    $name = 'John'; echo "Hello, $name"; // Output: Hello, John
  3. Heredoc syntax (<<<)

    • Acts like double quotes

    $name = 'John'; echo <<
  4. Nowdoc syntax (<<<')

    • Acts like single quotes

    $name = 'John'; echo <<<'TEXT' Hello, $name TEXT;

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:

$age = 30; echo "I am $age years old."; // I am 30 years old.

String Concatenation

Use the dot operator (.):

$first = "Hello"; $second = "World"; echo $first . " " . $second; // Hello World