<?php
declare(strict_types=1);
$cases = [];
// Case 1: String variables, single vs double quotes, and concatenation operator (.)
$txt = "Hello world!";
$txtSingle = 'Hello world!';
$txt1 = "Hello world!";
$txt2 = "What a nice day!";
$joined = $txt1 . " " . $txt2;
$c1Actual = [
'txt' => $txt,
'quotes_equal' => $txt === $txtSingle,
'joined' => $joined,
];
$c1Expected = [
'txt' => 'Hello world!',
'quotes_equal' => true,
'joined' => 'Hello world! What a nice day!',
];
$cases[] = [
'name' => 'string_var_and_concatenation',
'passed' => $c1Actual === $c1Expected,
'expected' => $c1Expected,
'actual' => $c1Actual,
];
// Case 2: strlen() returns UTF-8 byte length vs mb_strlen() returning character count
$c2Actual = [
'ascii_strlen' => strlen('Hello world!'),
'utf8_strlen_bytes' => strlen('你好PHP'),
'utf8_mb_strlen_chars' => mb_strlen('你好PHP', 'UTF-8'),
];
$c2Expected = [
'ascii_strlen' => 12,
'utf8_strlen_bytes' => 9,
'utf8_mb_strlen_chars' => 5,
];
$cases[] = [
'name' => 'strlen_bytes_vs_mb_strlen_chars',
'passed' => $c2Actual === $c2Expected,
'expected' => $c2Expected,
'actual' => $c2Actual,
];
// Case 3: strpos() 0-based index, index-0 strict check (!== false), and not-found false
$posWorld = strpos('Hello world!', 'world');
$posHello = strpos('Hello world!', 'Hello');
$posMissing = strpos('Hello world!', 'PHP');
$c3Actual = [
'world_pos' => $posWorld,
'hello_pos' => $posHello,
'hello_found_strict' => $posHello !== false,
'missing_is_false' => $posMissing === false,
];
$c3Expected = [
'world_pos' => 6,
'hello_pos' => 0,
'hello_found_strict' => true,
'missing_is_false' => true,
];
$cases[] = [
'name' => 'strpos_zero_index_and_not_found',
'passed' => $c3Actual === $c3Expected,
'expected' => $c3Expected,
'actual' => $c3Actual,
];
// Case 4: Modern PHP 8.0+ string inspection helpers (str_contains, str_starts_with, str_ends_with)
$c4Actual = [
'contains_world' => str_contains('Hello world!', 'world'),
'contains_php' => str_contains('Hello world!', 'PHP'),
'starts_hello' => str_starts_with('Hello world!', 'Hello'),
'ends_bang' => str_ends_with('Hello world!', '!'),
];
$c4Expected = [
'contains_world' => true,
'contains_php' => false,
'starts_hello' => true,
'ends_bang' => true,
];
$cases[] = [
'name' => 'php8_str_contains_helpers',
'passed' => $c4Actual === $c4Expected,
'expected' => $c4Expected,
'actual' => $c4Actual,
];
echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
本例需在 Windows x64、PHP 8.4 本地 CLI 环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、PHP 8.4 本地 CLI 环境。
入口文件:projects/php-string-lab/explore-string.php
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-string.php,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、PHP 8.4 本地 CLI 环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联95章) · 含当前章节或实例 · mbskycom202612a1232.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1307.zip