PHP: 文字列の詳細
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 |
▶ サンプル: 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
?>
💡 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:
▶ サンプル: Core String Operations
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)
?>
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
?>
▶ サンプル: Combined String Operations
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()
?>
🔥 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(...)).
❓ よくある質問
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.📖 まとめ
- Single quotes don't parse variables/escape sequences (use for plain text); double quotes do (use when embedding variables)
- Use
.to concatenate strings and.=to append (not+) - Heredoc for multi-line templates (parses variables); Nowdoc for multi-line plain text (doesn't parse)
strlen/strpos/substr/str_replace/trimare the most common functionsexplodesplits a string into an array;implodejoins an array into a string- Always check
strpos()with!== false— never withif (strpos())
📝 練習問題
- Take a user-input string and process it: strip leading/trailing whitespace → convert everything to lowercase → replace all spaces with underscores → output the result.
- Use
explodeto split a comma-separated tag string into an array, deduplicate it, then useimplodeto rejoin and output it. - Write a function that accepts an email address string and uses
strposandsubstrto extract the username part (everything before the@).