W3docs

PHP Strings: An In-Depth Guide

In this article, we will dive deep into the world of PHP strings and explore all its features. PHP strings are a fundamental aspect of PHP programming and an

A string is a sequence of characters used to store and manipulate text — names, messages, HTML, JSON, file contents, and much more. Strings are one of PHP's core data types, and almost every PHP program touches them. This guide covers how to create strings, the crucial difference between single and double quotes, concatenation, accessing individual characters, the most useful built-in functions, escape sequences, and the multi-line Heredoc and Nowdoc syntaxes — with runnable examples throughout.

What Is a PHP String?

A string is text wrapped in quotes and stored in a variable. PHP gives you four ways to write one: single quotes, double quotes, Heredoc, and Nowdoc. The two quote styles are the ones you'll use most:

<?php
$single = 'Hello World';
$double = "Hello World";

echo $single; // Hello World
echo "\n";
echo $double; // Hello World

Strings have no fixed length limit other than available memory, so a string can hold a single character or an entire document.

Single vs. Double Quotes

This is the most important distinction to learn early, because choosing the wrong quote style is a common source of bugs. Double quotes parse escape sequences and interpolate variables; single quotes treat almost everything literally.

<?php
$name = 'Alice';

echo "Hello $name\n"; // Hello Alice  (variable + newline parsed)
echo 'Hello $name\n'; // Hello $name\n  (printed literally)

When the variable touches other characters, wrap it in curly braces so PHP knows where the name ends:

<?php
$item = 'book';

echo "I bought 3 {$item}s\n"; // I bought 3 books

Single quotes are marginally faster and safer when you don't need interpolation — prefer them for fixed text. Use double quotes (or Heredoc) when you need to embed variables or escape sequences.

String Concatenation

Joining strings into one is called concatenation. PHP uses the dot (.) operator, and .= appends to an existing string:

<?php
$first = 'Hello';
$last  = 'World';

$greeting = $first . ' ' . $last;
echo $greeting; // Hello World

$greeting .= '!';
echo "\n" . $greeting; // Hello World!

Note PHP uses . for concatenation, not + — using + on two strings attempts numeric addition and is almost never what you want.

Accessing Characters

A string behaves like an array of characters. You can read any character by its zero-based index using square brackets:

<?php
$word = 'PHP';

echo $word[0];  // P
echo $word[2];  // P
echo $word[-1]; // P  (negative index counts from the end)

To get the string's length, use strlen:

<?php
echo strlen('Hello World'); // 11 (the space counts)

Common String Functions

PHP ships with a rich library of string functions. Here are the ones you'll reach for most often, each linking to a dedicated chapter:

FunctionPurpose
strlenLength of a string (in bytes)
strposPosition of the first occurrence of a substring
str_replaceReplace all occurrences of a substring
strtoupper / strtolowerChange case
substrExtract part of a string
trimStrip whitespace from both ends
explode / implodeConvert between strings and arrays
sprintfFormat a string from a template

A quick tour:

<?php
$text = '  The quick brown fox  ';

echo strlen($text);                  // 23
echo "\n";
echo strpos($text, 'quick');         // 6
echo "\n";
echo str_replace('quick', 'slow', trim($text)); // The slow brown fox
echo "\n";
echo strtoupper(trim($text));        // THE QUICK BROWN FOX
echo "\n";
echo substr(trim($text), 0, 3);      // The

sprintf builds a string from a template, which is handy for numbers and padding:

<?php
$price = 9.5;
echo sprintf('Total: $%.2f', $price); // Total: $9.50

Working with Unicode

Standard functions like strlen and strpos count bytes, not characters. For text containing accented letters, emoji, or non-Latin scripts, use the multi-byte mb_* equivalents from the mbstring extension so multi-byte characters are counted correctly:

<?php
$word = 'café';

echo strlen($word);    // 5  (é is 2 bytes in UTF-8)
echo "\n";
echo mb_strlen($word); // 4  (correct character count)

Escape Sequences

Inside double-quoted strings, a backslash starts an escape sequence — a way to write characters that are hard to type or that would otherwise be parsed. The common ones:

SequenceMeaning
\nNewline
\tTab
\"Literal double quote
\\Literal backslash
\$Literal dollar sign (suppress interpolation)
<?php
echo "Line 1\nLine 2";       // prints on two lines
echo "\n";
echo "Price: \$5";           // Price: $5
echo "\n";
echo "She said \"hello\"";   // She said "hello"

Single-quoted strings recognize only \' (a literal quote) and \\; everything else, including \n, is printed verbatim.

Heredoc and Nowdoc

When you need a long, multi-line string, Heredoc and Nowdoc are cleaner than escaping newlines by hand.

Heredoc behaves like a double-quoted string: variables are interpolated and escape sequences work. Open it with <<< followed by an identifier, and close it with that same identifier on its own line:

<?php
$name = 'Alice';

$message = <<<EOT
Dear $name,
Welcome aboard!
EOT;

echo $message;
// Dear Alice,
// Welcome aboard!

Nowdoc behaves like a single-quoted string — no interpolation, no escape parsing. The only difference in syntax is that the opening identifier is wrapped in single quotes:

<?php
$name = 'Alice';

$message = <<<'EOT'
Dear $name,
Welcome aboard!
EOT;

echo $message;
// Dear $name,
// Welcome aboard!

Use Heredoc for templated output (emails, HTML blocks) and Nowdoc when you want the text left exactly as written.

Summary

PHP strings are the backbone of working with text. The essentials to remember:

  • Use single quotes for literal text and double quotes (or Heredoc) when you need variable interpolation or escape sequences.
  • Concatenate with the . operator, not +.
  • Reach for built-in functions like strlen, substr, str_replace, and explode instead of reinventing them.
  • Use the mb_* functions whenever text may contain non-ASCII characters.

Next, learn how to display strings and other values with echo and print, or explore PHP numbers and arrays.

Practice

Practice
In PHP, which of the following statements about strings are correct?
In PHP, which of the following statements about strings are correct?
Was this page helpful?