PHP 字符串变量详解

字符串是 PHP 中最常用的数据类型之一,用于存储和操作文本数据。理解字符串的处理对于 PHP 开发至关重要。

PHP 字符串基础

字符串是由字符组成的序列,用于表示文本数据。在 PHP 中,字符串可以用单引号、双引号、HEREDOC 或 NOWDOC 语法定义。

字符串定义方式

<?php
// 单引号字符串
$str1 = 'Hello World!';
echo $str1 . "<br>";

// 双引号字符串(支持变量解析)
$name = "John";
$str2 = "Hello $name!";
echo $str2 . "<br>";

// HEREDOC 语法(支持变量解析)
$str3 = <<<EOD
这是一个多行字符串
可以包含变量:$name
以及换行符。
EOD;
echo $str3 . "<br>";

// NOWDOC 语法(不解析变量)
$str4 = <<<'EOD'
这是一个多行字符串
不会解析变量:$name
EOD;
echo $str4;
?>

字符串连接运算符

PHP 使用点号 (.) 作为字符串连接运算符,用于将多个字符串连接在一起。

字符串连接示例

<?php
// 基本连接
$txt1 = "Hello";
$txt2 = "World";
echo $txt1 . " " . $txt2 . "!<br>"; // 输出: Hello World!

// 连接变量和字符串
$firstName = "张";
$lastName = "三";
$fullName = $firstName . $lastName;
echo "姓名: " . $fullName . "<br>";

// 连续连接
$message = "欢迎" . "来到" . "我们的" . "网站!";
echo $message . "<br>";

// 连接运算符优先级
$result = "数字: " . 5 + 3; // 注意运算符优先级
echo $result . "<br>"; // 输出: 3(因为 "数字: 5" 转换为 0 + 3)

// 正确的写法
$result = "数字: " . (5 + 3);
echo $result . "<br>"; // 输出: 数字: 8
?>

提示:连接运算符的优先级低于算术运算符,在复杂表达式中建议使用括号明确运算顺序。

常用字符串函数

PHP 提供了丰富的字符串处理函数,以下是一些最常用的函数:

strlen() - 获取字符串长度

字符串长度示例

<?php
// 基本用法
echo strlen("Hello world!"); // 输出: 12

// 中文字符串长度(注意编码)
$chinese = "你好世界";
echo strlen($chinese) . "<br>"; // 输出: 12(UTF-8 中每个中文占3字节)

// 使用 mb_strlen 获取字符数
echo mb_strlen($chinese, 'UTF-8') . "<br>"; // 输出: 4

// 在实际应用中使用
$password = "mypassword123";
if (strlen($password) < 8) {
    echo "密码长度不足!<br>";
} else {
    echo "密码长度符合要求!<br>";
}
?>

strpos() - 查找字符串位置

字符串查找示例

<?php
// 查找子字符串位置
echo strpos("Hello world!", "world"); // 输出: 6

// 严格检查查找结果
$text = "Hello world!";
$position = strpos($text, "world");
if ($position !== false) {
    echo "找到 'world',位置在: " . $position . "<br>";
} else {
    echo "未找到 'world'<br>";
}

// 从指定位置开始查找
echo strpos("Hello world! Hello again!", "Hello", 1) . "<br>"; // 输出: 13

// 不区分大小写查找
echo stripos("Hello World!", "world") . "<br>"; // 输出: 6

// 反向查找
echo strrpos("Hello world! Hello again!", "Hello") . "<br>"; // 输出: 13
?>

str_replace() - 字符串替换

字符串替换示例

<?php
// 基本替换
$text = "Hello world!";
$newText = str_replace("world", "PHP", $text);
echo $newText . "<br>"; // 输出: Hello PHP!

// 多对多替换
$text = "苹果,香蕉,橙子";
$fruits = array("苹果", "香蕉", "橙子");
$replace = array("apple", "banana", "orange");
echo str_replace($fruits, $replace, $text) . "<br>";

// 统计替换次数
$count = 0;
$text = "猫吃鱼,猫睡觉,猫玩耍";
$newText = str_replace("猫", "狗", $text, $count);
echo $newText . ",替换了 " . $count . " 次<br>";

// 不区分大小写替换
$text = "Hello WORLD!";
echo str_ireplace("world", "PHP", $text) . "<br>"; // 输出: Hello PHP!
?>

更多实用字符串函数

大小写转换

大小写转换示例

<?php
$text = "Hello World!";

// 转换为小写
echo strtolower($text) . "<br>"; // 输出: hello world!

// 转换为大写
echo strtoupper($text) . "<br>"; // 输出: HELLO WORLD!

// 首字母大写
echo ucfirst("hello world") . "<br>"; // 输出: Hello world

// 每个单词首字母大写
echo ucwords("hello world") . "<br>"; // 输出: Hello World

// 首字母小写
echo lcfirst("Hello World") . "<br>"; // 输出: hello World
?>

字符串截取和修剪

截取和修剪示例

<?php
// 字符串截取
$text = "Hello World!";
echo substr($text, 0, 5) . "<br>"; // 输出: Hello
echo substr($text, 6) . "<br>";    // 输出: World!
echo substr($text, -6) . "<br>";   // 输出: World!

// 多字节安全截取
$chinese = "你好世界,欢迎学习PHP";
echo mb_substr($chinese, 0, 4, 'UTF-8') . "<br>"; // 输出: 你好世界

// 字符串修剪
$text = "   Hello World!   ";
echo "[" . trim($text) . "]<br>";     // 输出: [Hello World!]
echo "[" . ltrim($text) . "]<br>";    // 输出: [Hello World!   ]
echo "[" . rtrim($text) . "]<br>";    // 输出: [   Hello World!]

// 去除特定字符
$text = "###Hello World!###";
echo trim($text, "#") . "<br>"; // 输出: Hello World!
?>

字符串分割和连接

分割和连接示例

<?php
// 字符串分割为数组
$text = "apple,banana,orange";
$fruits = explode(",", $text);
print_r($fruits);
echo "<br>";

// 限制分割次数
$text = "one:two:three:four";
$parts = explode(":", $text, 3);
print_r($parts);
echo "<br>";

// 数组连接为字符串
$array = array("apple", "banana", "orange");
echo implode(", ", $array) . "<br>"; // 输出: apple, banana, orange

// 使用不同连接符
echo implode(" - ", $array) . "<br>"; // 输出: apple - banana - orange

// 正则表达式分割
$text = "apple123banana456orange";
$parts = preg_split("/\d+/", $text);
print_r($parts);
?>

字符串格式化

printf() 和 sprintf()

格式化输出示例

<?php
// printf - 直接输出
$number = 123;
$text = "Hello";
printf("数字: %d, 字符串: %s<br>", $number, $text);

// sprintf - 返回格式化字符串
$formatted = sprintf("价格: $%.2f", 19.99);
echo $formatted . "<br>";

// 多种格式化选项
printf("十进制: %d<br>", 123);
printf("浮点数: %.2f<br>", 123.456);
printf("二进制: %b<br>", 123);
printf("八进制: %o<br>", 123);
printf("十六进制: %x<br>", 123);
printf("字符: %c<br>", 65); // A

// 填充和对齐
printf("[%-10s]<br>", "left");    // 左对齐
printf("[%10s]<br>", "right");   // 右对齐
printf("[%010d]<br>", 123);     // 用0填充
?>

数字格式化

数字格式化示例

<?php
// 数字格式化
$number = 1234567.89;

echo number_format($number) . "<br>";           // 输出: 1,234,568
echo number_format($number, 2) . "<br>";       // 输出: 1,234,567.89
echo number_format($number, 2, ',', ' ') . "<br>"; // 输出: 1 234 567,89

// 货币格式化
setlocale(LC_MONETARY, 'en_US');
// echo money_format('%.2n', $number) . "<br>"; // 需要系统支持

// 简单货币格式化函数
function formatCurrency($amount) {
    return '$' . number_format($amount, 2);
}
echo formatCurrency(1234.56) . "<br>"; // 输出: $1,234.56
?>

PHP 7+ 字符串新特性

空合并运算符与字符串

空合并运算符示例

<?php
// PHP 7+ 空合并运算符
$username = $_GET['username'] ?? '匿名用户';
echo "欢迎, " . $username . "<br>";

// 空合并赋值运算符 (PHP 7.4+)
$config = [];
$config['title'] ??= '默认标题';
echo $config['title'] . "<br>";

// 在字符串操作中使用
$text = null;
$result = $text ?? '默认文本';
echo $result . "<br>";
?>

PHP 8 字符串函数增强

PHP 8 新函数示例

<?php
// PHP 8+ str_contains()
$text = "Hello World!";
if (str_contains($text, "World")) {
    echo "包含 'World'<br>";
}

// PHP 8+ str_starts_with()
if (str_starts_with($text, "Hello")) {
    echo "以 'Hello' 开头<br>";
}

// PHP 8+ str_ends_with()
if (str_ends_with($text, "!")) {
    echo "以 '!' 结尾<br>";
}

// 实际应用
$email = "user@example.com";
if (str_ends_with($email, ".com")) {
    echo "这是一个 .com 邮箱<br>";
}

$url = "https://example.com";
if (str_starts_with($url, "https://")) {
    echo "这是一个安全链接<br>";
}
?>

字符串安全与转义

HTML 转义

防止 XSS 攻击

<?php
// 用户输入(可能包含恶意脚本)
$userInput = '<script>alert("XSS")</script><p>正常内容</p>';

// 不安全输出
// echo $userInput; // 危险!会执行脚本

// 安全输出 - HTML 转义
echo htmlspecialchars($userInput) . "<br>";

// 各种转义选项
echo htmlspecialchars($userInput, ENT_QUOTES) . "<br>"; // 转义单引号和双引号
echo htmlspecialchars($userInput, ENT_HTML5) . "<br>";  // HTML5 规范

// URL 编码
$urlParam = "Hello World & More!";
echo urlencode($urlParam) . "<br>"; // 输出: Hello+World+%26+More%21
?>

数据库转义

防止 SQL 注入

<?php
// 注意:实际开发中应使用预处理语句,这里仅为演示转义

$userInput = "O'Reilly";

// 使用 addslashes(不推荐用于数据库)
echo addslashes($userInput) . "<br>"; // 输出: O\'Reilly

// 对于 MySQL(不推荐,使用预处理语句更好)
// $escaped = mysqli_real_escape_string($connection, $userInput);

// 最佳实践:使用预处理语句
class DatabaseExample {
    public function safeQuery($username) {
        // 使用预处理语句,参数化查询
        // $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
        // $stmt->execute([$username]);
        return "安全查询: " . $username;
    }
}

$db = new DatabaseExample();
echo $db->safeQuery("test' OR '1'='1") . "<br>";
?>

实际应用示例

用户输入处理

表单数据处理

<?php
// 模拟用户输入
$_POST['username'] = "  John Doe  ";
$_POST['email'] = "JOHN@EXAMPLE.COM";
$_POST['bio'] = "这是一段个人简介。\n它包含多行内容。";

// 处理用户输入
function processUserInput($data) {
    $processed = [];

    // 去除首尾空格
    $processed['username'] = trim($data['username']);

    // 邮箱转为小写
    $processed['email'] = strtolower(trim($data['email']));

    // 简介处理:去除多余空格,限制长度
    $bio = trim($data['bio']);
    $bio = preg_replace('/\s+/', ' ', $bio); // 合并多个空格
    $processed['bio'] = mb_substr($bio, 0, 200, 'UTF-8'); // 限制长度

    return $processed;
}

$result = processUserInput($_POST);
print_r($result);
?>

字符串模板

动态内容生成

<?php
// 邮件模板
function generateEmailTemplate($userName, $productName, $price) {
    $template = <<<EMAIL
亲爱的 {$userName},

感谢您购买 {$productName}!

订单金额:\${$price}

如有问题,请联系我们。

感谢,
客服团队
EMAIL;

    return $template;
}

echo generateEmailTemplate("张三", "PHP教程", "99.00");
?>

字符串性能优化

性能提示:

  • 对于大量字符串连接,使用 implode() 比多次使用 . 更高效
  • 使用单引号定义不包含变量的字符串,性能稍好
  • 避免在循环中进行不必要的字符串操作
  • 对于中文字符串处理,使用多字节函数(mb_*)
  • 使用输出缓冲减少多次 echo 调用

高效字符串连接

<?php
// 低效方式
$result = "";
for ($i = 0; $i < 1000; $i++) {
    $result .= "item " . $i . ",";
}

// 高效方式
$items = [];
for ($i = 0; $i < 1000; $i++) {
    $items[] = "item " . $i;
}
$result = implode(",", $items);
?>

总结

  • 字符串是 PHP 中最常用的数据类型,支持单引号、双引号、HEREDOC 和 NOWDOC 语法
  • 使用点号 (.) 进行字符串连接操作
  • 掌握常用字符串函数:strlen(), strpos(), str_replace()
  • PHP 7/8 引入了新的字符串函数和运算符
  • 始终注意字符串安全性,防止 XSS 和 SQL 注入攻击
  • 对于中文字符串处理,使用多字节函数确保正确性
  • 优化字符串操作性能,特别是在处理大量数据时

完整的 PHP 字符串参考手册

如需查看所有字符串函数的完整参考手册,请访问我们的 PHP String 参考手册

该参考手册提供了每个函数的详细描述、参数说明和应用实例!