PHP具有丰富的字符串支持:不同的引号风格(具有不同的插值行为)、连接和大量的字符串函数库。理解引号差异和函数集是日常知识。
为什么这很重要
php
<?php
$name = "Ann";
'Hello $name'; // 'Hello $name' — SINGLE quotes: literal, NO interpolation
;
;
关键区别:双引号进行变量插值($name被替换为其值),单引号是字面量(更快,没有插值)。对于复杂表达式(如对象属性),使用{}。
$greeting = "Hello, " . $name . "!"; // . is the concatenation operator (NOT +)
$greeting .= " Welcome."; // .= appends
PHP使用.进行字符串连接(不是+,这是数字运算)——这是一个常见的混淆点。
$html = <<<HTML
<div>$name</div> // heredoc — interpolates (like double quotes)
HTML;
$raw = <<<'TEXT'
Literal $name // nowdoc (quoted label) — no interpolation (like single quotes)
TEXT;
strlen($s); // length
strtoupper($s); strtolower($s);
trim($s); // remove surrounding whitespace
str_replace("old", "new", $s);
strpos($s, "needle"); // find position (false if not found — use === false)
substr($s, 0, 5); // extract a substring
explode(",", $csv); // split into an array
implode(",", $array); // join an array into a string
sprintf("%.2f", 3.14159); // formatted output → "3.14"
str_contains($s, "x"); // PHP 8: cleaner substring check
mb_strlen($s); // ✅ correct length for multi-byte (UTF-8) text
strlen($s); // ⚠️ counts BYTES, not characters — wrong for non-ASCII
对于非ASCII/Unicode文本,使用**mb_***函数(mb_strlen、mb_substr)——普通函数计算字节,而不是字符,会在多字节文本上损坏。
字符串操作在网络开发中很普遍(构建HTML、处理输入、格式化输出、解析数据),因此理解PHP的字符串处理是日常必备知识。
最重要的实践要点:单引号与双引号的区别(双引号进行变量插值,单引号是字面量)是基础性的,也是初学者常见的混淆点;PHP使用**.进行连接**(不是+);PHP有大量的字符串函数库用于常见任务(搜索、替换、分割/连接、格式化)。
至关重要的是,对于任何处理非英文/Unicode文本的应用,了解使用**mb_*(多字节)函数**而不是普通函数(计算字节而不是字符,会破坏多字节文本)可以防止实际bug。
PHP的引号行为、连接和字符串函数库的熟练掌握——包括多字节安全——是网络开发中常见字符串处理工作的核心知识。