PHP: Strings in Depth

PHP is exceptionally strong at handling strings — after all, it was originally built for generating HTML text. This lesson covers every core string operation you'll use daily.

1. Single Quotes vs. Double Quotes

PHP
<?php
$name = "John";

// Single quotes: literal output — no variable parsing
echo 'Hello, $name';     // Hello, $name (variable not parsed)

// Double quotes: variables and escape sequences are parsed
echo "Hello, $name";     // Hello, John (variable parsed)
echo "Hello, {$name}";   // Hello, John (curly braces clarify the variable boundary — recommended)
?>
Feature Single Quotes '' Double Quotes ""
Parses variables
Parses escape sequences (\n \t) ❌ (only \\ \')
Speed Slightly faster (no parsing) Slightly slower
Best for Plain text, config values Embedding variables

▶ Example: Curly Braces Clarify Variable Boundaries

PHP
<?php
$drink = "coffee";
echo "Give me a {$drink} latte";   // Give me a coffee latte ✅
echo "Give me a $drink latte";     // Warning: Undefined variable $drink_latte
// When characters immediately follow a variable, use curly braces
?>
▶ Try it Yourself

Output:

TEXT 📖 Display only
Give me a coffee latte
💡 Tip: When embedding variables inside double quotes, always use the {$var} curly brace syntax. It's the safest and most readable approach.


2. Heredoc and Nowdoc

When you need to write multi-line strings, Heredoc and Nowdoc are far more elegant than repeatedly concatenating single or double quotes:

PHP
<?php
$title = "PHP Tutorial";

// Heredoc: the multi-line equivalent of double quotes (parses variables)
$html = <<<HTML
<div class="header">
    <h1>{$title}</h1>
    <p>This is lesson one</p>
</div>
HTML;

// Nowdoc: the multi-line equivalent of single quotes (no variable parsing)
$config = <<<'CONFIG'
database_host = localhost
database_name = $db_name
CONFIG;
// $db_name is output literally — not parsed

echo $html;
?>
💡 Tip: Heredoc is perfect for outputting large blocks of HTML templates inside PHP. The closing marker (HTML; in the example above) must be at the start of the line with no leading whitespace or indentation.


3. String Concatenation

PHP uses the dot . to concatenate strings (not + — that's for math):

PHP
<?php
// Concatenate with .
$greeting = "Hello, " . "World!";
echo $greeting;  // Hello, World!

// Concatenate variables
$name = "John";
echo "Welcome, " . $name;  // Welcome, John

// .= for append concatenation
$text = "PHP";
$text .= " Tutorial";     // Equivalent to $text = $text . " Tutorial"
echo $text;               // PHP Tutorial
?>
🔥 Common Mistake: In PHP, + is mathematical addition; . is string concatenation. "10" + "5" = 15 (numeric addition), while "10" . "5" = "105" (string concatenation).


4. Essential String Functions

PHP has over 100 built-in string functions. Here are the ones you'll use most often:

▶ Example: Core String Operations

Output:

TEXT 📖 Display only
Welcome, JOHN!
PHP
<?php
$str = "Hello PHP World";

// Length
echo strlen($str);            // 16

// Find position (returns false if not found)
echo strpos($str, "PHP");     // 6 (0-based)
var_dump(strpos($str, "Java")); // bool(false)

// Substring
echo substr($str, 6, 3);      // "PHP" (3 chars starting at position 6)
echo substr($str, -5);        // "World" (last 5 characters)

// Replace
echo str_replace("World", "Earth", $str);  // Hello PHP Earth
echo str_ireplace("php", "JS", $str);      // Hello JS World (case-insensitive)

// Trim whitespace
$input = "  hello  ";
echo trim($input);            // "hello" (both sides)
echo ltrim($input);           // "hello  " (left only)
echo rtrim($input);           // "  hello" (right only)

// Case conversion
echo strtoupper("hello");     // HELLO
echo strtolower("HELLO");     // hello
echo ucfirst("hello world");  // Hello world (first letter uppercase)
echo ucwords("hello world");  // Hello World (every word capitalized)
?>

Output:

TEXT 📖 Display only
16
6
bool(false)
PHP
World
Hello PHP Earth
Hello JS World
hello
hello  
  hello
HELLO
hello
Hello world
Hello World

5. Splitting and Joining Strings

PHP
<?php
// explode: string → array (split by delimiter)
$tags = "PHP,MySQL,Redis";
$tagArray = explode(",", $tags);
var_dump($tagArray);  // ["PHP", "MySQL", "Redis"]

// implode / join: array → string (join with delimiter)
$arr = ["apple", "banana", "orange"];
echo implode(", ", $arr);  // apple, banana, orange
echo join(" - ", $arr);    // apple - banana - orange (join is an alias for implode)

// str_split: split by length
$chars = str_split("Hello", 2);
var_dump($chars);  // ["He", "ll", "o"]
?>

6. String Formatting

PHP
<?php
// sprintf: formatted string (like C)
$name = "John";
$score = 92.5;
echo sprintf("%s scored %.1f points", $name, $score);  // John scored 92.5 points

// Common format placeholders
// %s — string
// %d — integer
// %f — float
// %.2f — float with 2 decimal places

// number_format: thousands separator formatting
echo number_format(1234567.89, 2);  // 1,234,567.89

// nl2br: newlines → <br> (essential for displaying database text on a web page)
$text = "Line one\nLine two\nLine three";
echo nl2br($text);
// Output: Line one<br>Line two<br>Line three
?>

▶ Example: Combined String Operations

Output:

TEXT 📖 Display only
Username cannot contain 'admin'
Welcome, " . strtoupper(Alice) . "!
PHP
<?php
// Scenario: processing a user-entered name
$input = "  John  ";
$name = trim($input);           // Remove whitespace

// Check for forbidden words
if (strpos($name, "admin") !== false) {
    echo "Username cannot contain 'admin'";
} else {
    echo "Welcome, " . strtoupper($name) . "!";  // Welcome, JOHN!
}
// Important: strpos returns a position, and position 0 is a valid value
// Always use !== false to check, never !strpos()
?>

Output:

TEXT 📖 Display only
Output displayed
🔥 Common Mistake: strpos() returns 0 when the match is at position 0, and in PHP 0 == false evaluates to true! Always use strict comparison !== false to check "was it found" — never use if (strpos(...)).

❓ FAQ

Q When should I use single quotes vs. double quotes?
A Use single quotes when you don't need to embed variables (slightly faster). Use double quotes when you need variables or escape sequences. For large HTML templates, use Heredoc.
Q What's the difference between explode() and str_split()?
A explode("delimiter", $str) splits by a specified delimiter. str_split($str, length) splits into fixed-length chunks.
Q strpos returns 0, and 0 is false in an if statement — what do I do?
A This is one of PHP's most common traps. Always use if (strpos($haystack, $needle) !== false) — add !== for strict comparison.

📖 Summary

📝 Exercises

  1. Take a user-input string and process it: strip leading/trailing whitespace → convert everything to lowercase → replace all spaces with underscores → output the result.
  2. Use explode to split a comma-separated tag string into an array, deduplicate it, then use implode to rejoin and output it.
  3. Write a function that accepts an email address string and uses strpos and substr to extract the username part (everything before the @).
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏