ZetCode

PHP字符串

最后修改于 2025 年 4 月 16 日

PHP 的 string 是一种用于处理文本的基本数据类型。字符串是由用于存储和操作文本数据的字符序列组成的。 PHP 提供了广泛的字符串操作和处理函数。

基本定义

字符串是一系列字符,其中每个字符都与一个字节相同。 PHP 字符串的大小可以高达 2GB。 字符串可以通过四种方式创建:单引号、双引号、heredoc 语法和 nowdoc 语法。

单引号字符串按字面意思显示内容。双引号字符串执行变量插值和特殊字符解释。 Heredoc 的行为类似于双引号字符串。 Nowdoc 的行为类似于单引号字符串。

PHP 提供了 100 多个内置字符串函数,用于常见的操作,如搜索、替换、格式化、比较和修改字符串。

基本字符串创建

此示例演示了在 PHP 中创建字符串的不同方法。

basic_string.php
<?php

declare(strict_types=1);

$single = 'Single quoted string';
$double = "Double quoted string with $single";
$heredoc = <<<EOT
Heredoc string (like double quotes)
Can span multiple lines
EOT;
$nowdoc = <<<'EOT'
Nowdoc string (like single quotes)
No variable interpolation
EOT;

echo $single . "\n";
echo $double . "\n";
echo $heredoc . "\n";
echo $nowdoc . "\n";

该代码显示了四种字符串创建方法。单引号不插入变量。双引号会。 Heredoc 允许使用插值的多行字符串。 Nowdoc 用于没有插值的多行字符串。

字符串连接

此示例展示了如何使用连接来组合字符串。

concatenation.php
<?php

declare(strict_types=1);

$firstName = "John";
$lastName = "Doe";

// Using concatenation operator
$fullName = $firstName . " " . $lastName;
echo $fullName . "\n";

// Using concatenation assignment
$greeting = "Hello, ";
$greeting .= $fullName;
echo $greeting . "\n";

点 (.) 运算符连接字符串。 .= 运算符附加到现有字符串。 连接不会自动添加空格。 多个连接可以在一个表达式中链接在一起。

字符串长度和位置

此示例演示了查找字符串长度和字符位置。

length_position.php
<?php

declare(strict_types=1);

$text = "Hello World";

// Get string length
$length = strlen($text);
echo "Length: $length\n";

// Find character position
$pos = strpos($text, "World");
echo "'World' starts at position: $pos\n";

// Case-insensitive search
$pos = stripos($text, "world");
echo "'world' (case-insensitive) at: $pos\n";

strlen 返回字符串的字节长度。 strpos 查找子字符串的位置。 字符串位置从 0 开始。 stripos 执行不区分大小写的搜索。 如果未找到,这些函数将返回 false。

字符串修改

此示例显示了常见的字符串修改函数。

modification.php
<?php

declare(strict_types=1);

$text = "   php string tutorial   ";

// Trim whitespace
$trimmed = trim($text);
echo "Trimmed: '$trimmed'\n";

// Convert case
$lower = strtolower($trimmed);
$upper = strtoupper($trimmed);
echo "Lower: $lower\n";
echo "Upper: $upper\n";

// Replace text
$replaced = str_replace("tutorial", "guide", $trimmed);
echo "Replaced: $replaced\n";

trim 从两端删除空格。 strtolowerstrtoupper 更改大小写。 str_replace 替换文本。 这些函数返回新字符串,而不是修改原始字符串。

字符串拆分

此示例演示了将字符串分割成部分。

splitting.php
<?php

declare(strict_types=1);

$csv = "apple,banana,orange,grape";
$names = "John|Jane|Jim|Julie";

// Split by delimiter
$fruits = explode(",", $csv);
print_r($fruits);

// Split with limit
$limited = explode("|", $names, 2);
print_r($limited);

// Join array into string
$joined = implode(" - ", $fruits);
echo $joined . "\n";

explode 按分隔符将字符串分割成一个数组。 可选的 limit 参数限制分割的数量。 implode 将数组元素连接成一个字符串。 这些对于 CSV 处理和类似任务很有用。

字符串格式化

此示例展示了各种字符串格式化技术。

formatting.php
<?php

declare(strict_types=1);

$price = 19.99;
$count = 5;
$item = "widget";

// printf formatting
printf("Each %s costs \$%.2f. %d items cost \$%.2f.\n", 
    $item, $price, $count, $price * $count);

// sprintf returns formatted string
$message = sprintf("Thank you for purchasing %d %ss!", $count, $item);
echo $message . "\n";

// Number formatting
$formatted = number_format(1234567.89, 2, ".", ",");
echo "Formatted number: $formatted\n";

printf 输出格式化字符串。 sprintf 返回格式化字符串。 格式说明符如 %s (字符串)、%d (整数) 和 %f (浮点数) 控制格式化。 number_format 使用千位分隔符格式化数字。

多字节字符串函数

此示例演示了使用多字节 (UTF-8) 字符串。

multibyte.php
<?php

declare(strict_types=1);

$text = "こんにちは世界"; // Japanese "Hello World"

// Multibyte string length
$length = mb_strlen($text);
echo "Length in characters: $length\n";

// Multibyte substring
$sub = mb_substr($text, 0, 5);
echo "First 5 characters: $sub\n";

// Multibyte case conversion
$upper = mb_strtoupper("café");
echo "Uppercase: $upper\n";

// Check encoding
$encoding = mb_detect_encoding($text);
echo "Detected encoding: $encoding\n";

多字节函数正确处理 UTF-8 和其他编码。 mb_strlen 计算字符数,而不是字节数。 mb_substr 使用字符位置。 始终对多语言应用程序使用 mb_ 函数以避免编码问题。

最佳实践

来源

PHP 字符串文档

本教程涵盖了 PHP 字符串,并提供了实际示例,展示了字符串数据的创建、操作、格式化和多字节处理。

作者

我的名字是 Jan Bodnar,我是一位充满激情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直在撰写编程文章。 迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出 所有 PHP 教程