Skip to content

string — 字符串类型

概述

string 是 PHP 中最常用的标量类型之一,由一系列字符组成。PHP 的字符串是字节序列,内部没有固定的编码。字符串在 Web 开发中无处不在——HTML 输出、SQL 查询、JSON 数据、文件读写等都需要字符串处理。

前置知识

在阅读本节之前,你需要了解:

  • 单引号和双引号字符串的区别
  • 字符编码的基本概念(ASCII、UTF-8)
  • Heredoc 和 Nowdoc 语法

基础概念

四种字符串语法

语法变量解析转义序列性能用途
单引号 '...'不解析\\\'最快纯文本
双引号 "..."解析所有转义序列较慢需要嵌入变量
Heredoc <<<解析所有转义序列中等多行长文本
Nowdoc <<<'不解析原样输出较快多行纯文本

语法与代码

单引号与双引号

php
<?php
declare(strict_types=1);

$name = 'World';

// 单引号:不解析变量
$single = 'Hello, $name!';   // Hello, $name!
$single = 'It\'s a test';     // It's a test
$single = 'Line 1\nLine 2';  // Line 1\nLine 2(字面量)

// 双引号:解析变量和转义序列
$double = "Hello, {$name}!";  // Hello, World!
$double = "Line 1\nLine 2";   // 实际换行

// 双引号中的变量解析
$items = ['apple', 'banana'];
echo "I have $items[0]";           // I have apple
echo "Class {$name}";             // Class World
echo "Length: {strlen($name)}";   // Length: 5
echo "Upper: {strtoupper($name)}"; // Upper: WORLD

字符访问与修改

php
<?php
declare(strict_types=1);

$str = 'Hello';

echo $str[0];  // H
echo $str[-1]; // o(PHP 7.1+ 负索引)

// 修改字符
$str[0] = 'h';
echo $str; // hello

// 多字节字符串注意
$utf8 = '你好世界';
echo $utf8[0];             // 不是完整的字符
echo mb_substr($utf8, 0, 1); // '你'(正确方式)

常用字符串函数

php
<?php
declare(strict_types=1);

// 长度
echo strlen('hello');     // 5(字节长度)
echo mb_strlen('你好');   // 2(字符长度)

// 查找(PHP 8.0+)
echo str_contains('hello world', 'world'); // true
echo str_starts_with('hello', 'he');     // true
echo str_ends_with('hello', 'lo');       // true

// 替换
echo str_replace('world', 'PHP', 'hello world');

// 截取
echo substr('hello world', 0, 5);    // hello
echo mb_substr('你好世界', 0, 2);     // 你好

// 分割与连接
$array = explode(',', 'a,b,c');
echo implode('-', $array);             // a-b-c

// 大小写
echo strtolower('HELLO'); // hello
echo strtoupper('hello'); // HELLO
echo ucfirst('hello');   // Hello
echo ucwords('hello world'); // Hello World

// 去除空白
echo trim('  hello  ');       // hello

// HTML 处理
echo htmlspecialchars('<b>hi</b>'); // &lt;b&gt;hi&lt;/b&gt;
echo strip_tags('<b>hi</b>');        // hi

// 格式化
echo number_format(1234.567, 2);  // 1,234.57
echo sprintf('%s is %d years old', 'Alice', 30);

详细说明

数字字符串

php
<?php
declare(strict_types=1);

var_dump(is_numeric("42"));      // true
var_dump(is_numeric("3.14"));    // true
var_dump(is_numeric("42abc"));   // false

$result = "42" + 8;     // 50
$result = "3.14" * 2;    // 6.28

实战示例

字符串工具类

php
<?php
declare(strict_types=1);

class Str
{
    public static function truncate(string $str, int $length, string $suffix = '...'): string
    {
        if (mb_strlen($str) <= $length) {
            return $str;
        }
        return mb_substr($str, 0, $length) . $suffix;
    }

    public static function mask(string $str, int $visible = 2): string
    {
        $length = mb_strlen($str);
        if ($length <= $visible * 2) {
            return $str;
        }
        return mb_substr($str, 0, $visible)
             . str_repeat('*', $length - $visible * 2)
             . mb_substr($str, -$visible);
    }

    public static function contains(string $haystack, string $needle): bool
    {
        return str_contains($haystack, $needle);
    }
}

echo Str::truncate('Hello, World!', 5);   // Hello...
echo Str::mask('13800138000', 3);          // 138******000

注意事项

多字节字符操作

php
<?php
declare(strict_types=1);

// 错误:使用 strlen/substr 处理 UTF-8
echo strlen('你好');    // 6(字节数,不是字符数)

// 正确:使用 mb_* 函数
echo mb_strlen('你好');  // 2(字符数)
echo mb_substr('你好世界', 1, 2); // 好世

最佳实践

  1. 纯文本用单引号:不需要变量解析时使用单引号
  2. 使用 mb_ 函数处理 UTF-8*:不要用 strlen/substr
  3. str_starts_with/str_contains:PHP 8.0+ 使用新函数
  4. HTML 输出转义:始终使用 htmlspecialchars()
  5. sprintf 格式化:复杂字符串拼接使用 sprintf

下一节

下一节将详细介绍 Heredoc 和 Nowdoc 语法。

进阶用法

调试与测试技巧

php
<?php
declare(strict_types=1);

// 单元测试辅助函数
function createTestResource(): mixed
{
    return match (true) {
        default => new stdClass(),
    };
}

// 调试输出函数
function debugOutput(mixed , string  = ''): void
{
     =  ? ": " : '';
     .= print_r(, true);
    fwrite(STDERR,  . "\n");
}

// 性能基准测试
function benchmark(callable , int  = 1000): float
{
     = hrtime(true);
    for ($i = 0; $i < $iterations; $i++) {
        $fn();
    }
    return (hrtime(true) - $start) / 1e9;
}

日志记录实践

php
<?php
declare(strict_types=1);

/**
 * 简易日志记录器
 */
class SimpleLogger
{
    private string $logFile;
    private string $level = 'INFO';

    public function __construct(string $logFile)
    {
        $this->logFile = $logFile;
    }

    public function info(string $message, array $context = []): void
    {
        $this->log('INFO', $message, $context);
    }

    public function warning(string $message, array $context = []): void
    {
        $this->log('WARNING', $message, $context);
    }

    public function error(string $message, array $context = []): void
    {
        $this->log('ERROR', $message, $context);
    }

    private function log(string $level, string $message, array $context): void
    {
        $timestamp = date('Y-m-d H:i:s');
        $contextStr = $context ? ' ' . json_encode($context, JSON_UNESCAPED_UNICODE) : '';
        $line = "[{$timestamp}] [{$level}] {$message}{$contextStr}\n";
        file_put_contents($this->logFile, $line, FILE_APPEND | LOCK_EX);
    }
}

配置与环境检测

php
<?php
declare(strict_types=1);

// 环境检测工具
class EnvironmentChecker
{
    public static function checkRequirements(array $requirements): array
    {
        $results = [];
        foreach ($requirements as $name => $check) {
            $results[$name] = is_callable($check) ? $check() : false;
        }
        return $results;
    }

    public static function getSystemInfo(): array
    {
        return [
            'php_version' => PHP_VERSION,
            'os' => PHP_OS,
            'sapi' => PHP_SAPI,
            'memory_limit' => ini_get('memory_limit'),
            'max_execution_time' => ini_get('max_execution_time'),
            'loaded_extensions' => get_loaded_extensions(),
        ];
    }
}

常见问题排查

问题可能原因解决方案
连接超时网络问题/配置错误检查配置,增加超时时间
权限不足文件/目录权限使用 chmod/chown 修正
性能下降索引缺失/数据量大添加索引,优化查询
数据不一致并发冲突/事务残留使用锁机制和事务
内存溢出大数据集/未释放资源增大内存限制,分批处理

故障排除步骤

  1. 检查错误日志和异常信息
  2. 确认配置和环境是否正确
  3. 使用调试工具逐步排查
  4. 参考官方文档查找已知问题

版本兼容性说明

功能最低版本说明
基础功能PHP 8.1本文档基准版本
只读属性PHP 8.1public readonly 修饰符
枚举类型PHP 8.1enum 类型和 match 表达式
FiberPHP 8.1协程/轻量级并发
命名参数PHP 8.0foo(arg_name: value)
联合类型PHP 8.0`int
Null 安全运算符PHP 8.0$obj?->method()
析构器 promotionPHP 8.0__construct(public $x)
php
<?php
declare(strict_types=1);

// 版本兼容性检测
function ensureVersion(string $minVersion): void
{
    if (version_compare(PHP_VERSION, $minVersion, '<')) {
        throw new RuntimeException(
            sprintf('需要 PHP %s+, 当前版本: %s', $minVersion, PHP_VERSION)
        );
    }
}

ensureVersion('8.1.0');

参考链接