<?php
$text = 'sunny day';
$len = strlen($text); // 位元組長度: 9
$len = mb_strlen($text); // 字元長度 (多位元組安全): 9
?>
<?php
$article = 'BREAKING NEWS: In ultimate irony, man bites dog.';
$summary = mb_substr($article, 0, 40) . '...';
// "BREAKING NEWS: In ultimate irony, man bi..."
?>
<?php
$article = 'BREAKING NEWS: In ultimate irony, man bites dog.';
$wordCount = str_word_count($article); // 8
$charFreq = count_chars($article, 1); // 字元 ASCII 碼 => 次數
?>
<?php
$fh = fopen('contacts.csv', 'r');
while (($row = fgetcsv($fh, 1000, ',')) !== false) {
echo "Name: {$row[0]}, Email: {$row[1]}\n";
}
fclose($fh);
?>
<?php
$record = ['John', 'john@example.com', 'Taipei'];
$csvLine = implode(',', $record); // 簡單情況
// 正規 CSV (處理逗號、引號、換行)
$fh = fopen('php://temp', 'r+');
fputcsv($fh, $record);
rewind($fh);
$csvLine = stream_get_contents($fh);
fclose($fh);
?>
<?php
$text = 'Visit https://example.com and https://test.org/page';
$linked = preg_replace(
'/\bhttps?:\/\/\S+/',
'$0',
$text
);
// Visit https://example.com and ...
?>
<?php
$input = 'Hello World!
';
$clean = strip_tags($input); // 'Hello World! alert(1)'
$clean = strip_tags($input, ''); // 保留
: '
Hello World!
alert(1)'
?>
<?php
$pwd1 = 'secret';
$pwd2 = 'Secret';
if (strcmp($pwd1, $pwd2) === 0) { /* 完全相同 (區分大小寫) */ }
if (strcasecmp($pwd1, $pwd2) === 0) { /* 不區分大小寫相同 */ }
// 密碼驗證請用 password_verify()
?>
<?php
$comment = "Line 1\nLine 2\r\nLine 3";
echo nl2br($comment);
// Line 1
\nLine 2
\nLine 3
?>
<?php
$speech = "Four score and seven years ago our fathers brought forth...";
echo wordwrap($speech, 40, "\n", true);
/*
Four score and seven years ago our
fathers brought forth...
*/
?>
| 功能 | 單位元組 | 多位元組 (UTF-8) |
|---|---|---|
| 長度 | strlen | mb_strlen |
| 截取 | substr | mb_substr |
| 位置 | strpos | mb_strpos |
| 替換 | str_replace | mb_str_replace (PHP 8+) |
| 分割 | explode | mb_split / preg_split |
| 比較 | strcmp | mb_strcmp / Collator |