PHP 字符串

Single vs double quotes, common string functions, and multibyte handling.

Beginner
Key PointsDouble quotes interpolate variables and escapes; single quotes are almost literal.

单引号与双引号

The most basic difference: **single quotes only escape \' and \\**; double quotes interpolate variables and sequences like \n, \t, \$.

PHP
<?php
$name = "Tom";

echo 'Hello $name\n';        // 原样输出
echo "Hello $name\n";        // 解析变量
echo 'C:\path\to';           // \p \t 在单引号里不转义
echo "\n";
echo "价格: {$name}100\n";   // 用 {} 明确边界
echo "价格: $name" . "100\n"; // 或直接拼接
Output
Hello $name\nHello Tom
C:\path\to
价格: Tom100
价格: Tom100
The first line runs together because \n inside single quotes does not create a newline. That is the practical dividing line between the two quote styles.

Single quotes are marginally faster, but the difference is negligible. Follow the team convention.

常用函数

PHP
<?php
$s = "  Hello PHP  ";

echo strlen($s), "\n";                      // 含空格
echo strlen(trim($s)), "\n";                // 去首尾空白
echo strtoupper($s), "\n";
echo ucfirst("hello"), "\n";
echo strpos("hello php", "php"), "\n";      // 位置从 0 开始
echo substr("hello php", 6), "\n";
echo substr("hello php", -3), "\n";
echo str_replace("php", "PHP", "hello php"), "\n";
echo str_repeat("ab", 3), "\n";
echo str_pad("7", 3, "0", STR_PAD_LEFT), "\n";
echo implode("-", [1, 2, 3]), "\n";
echo sprintf("%05.2f", 3.14159), "\n";
echo number_format(1234567.891, 2), "\n";
Output
13
9
  HELLO PHP  
Hello
6
php
php
hello PHP
ababab
007
1-2-3
03.14
1,234,567.89

拆分与合并

PHP
<?php
$csv = "apple,banana,cherry";

$arr = explode(",", $csv);
print_r($arr);

echo implode(" | ", $arr), "\n";
echo count($arr), "\n";

// 限制拆分段数
print_r(explode(",", $csv, 2));

// str_split 按长度切
print_r(str_split("abcdef", 2));
Output
Array
(
    [0] => apple
    [1] => banana
    [2] => cherry
)
apple | banana | cherry
3
Array
(
    [0] => apple
    [1] => banana,cherry
)
Array
(
    [0] => ab
    [1] => cd
    [2] => ef
)

多字节字符串

strlen counts bytes; a UTF-8 Chinese character is 3 bytes. Use the mb_* family to count characters.

PHP
<?php
$cn = "你好世界";

echo strlen($cn), "\n";              // 字节数
echo mb_strlen($cn), "\n";           // 字符数
echo mb_substr($cn, 1, 2), "\n";     // 从第 2 个字取 2 个
echo mb_strtoupper("straße"), "\n";
Output
12
4
好世
STRASSE
substr() can slice a Chinese character in half and produce garbage. For any CJK text use mb_substr, mb_strlen, mb_strpos.

格式化输出

SpecifierMeaningExample
%s字符串sprintf("%s", "a") → a
%d十进制整数sprintf("%d", 3.9) → 3
%f浮点(默认 6 位小数)sprintf("%f", 1.5) → 1.500000
%.2f保留 2 位小数sprintf("%.2f", 1.005) → 1.00
%05d补零到 5 位sprintf("%05d", 42) → 00042
%x十六进制小写sprintf("%x", 255) → ff
%b二进制sprintf("%b", 5) → 101
%%百分号本身sprintf("%%") → %

sprintf returns the string, printf prints it. For numbers with units sprintf reads better than manual concatenation.

Friends & Partners