首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 字串處理 10 大實用技巧:長度、截取、統計、CSV、URL 連結、去標籤、比較、換行、自動換行

     編輯:PHP 綜合知識

1. 取得字串長度

<?php
$text = 'sunny day';
$len = strlen($text);        // 位元組長度: 9
$len = mb_strlen($text);     // 字元長度 (多位元組安全): 9
?>

2. 截取摘要 (加省略號)

<?php
$article = 'BREAKING NEWS: In ultimate irony, man bites dog.';
$summary = mb_substr($article, 0, 40) . '...';
// "BREAKING NEWS: In ultimate irony, man bi..."
?>

3. 統計單字數與字元頻率

<?php
$article = 'BREAKING NEWS: In ultimate irony, man bites dog.';
$wordCount = str_word_count($article); // 8
$charFreq = count_chars($article, 1);  // 字元 ASCII 碼 => 次數
?>

4. 解析 CSV (fgetcsv)

<?php
$fh = fopen('contacts.csv', 'r');
while (($row = fgetcsv($fh, 1000, ',')) !== false) {
    echo "Name: {$row[0]}, Email: {$row[1]}\n";
}
fclose($fh);
?>

5. 陣列轉 CSV 字串 (implode / fputcsv)

<?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);
?>

6. URL 自動轉超連結 (preg_replace)

<?php
$text = 'Visit https://example.com and https://test.org/page';
$linked = preg_replace(
    '/\bhttps?:\/\/\S+/',
    '$0',
    $text
);
// Visit https://example.com and ...
?>

7. 移除 HTML 標籤 (strip_tags)

<?php
$input = '

Hello World!

'; $clean = strip_tags($input); // 'Hello World! alert(1)' $clean = strip_tags($input, '

'); // 保留

: '

Hello World!

alert(1)' ?>

8. 字串比較 (strcmp / strcasecmp)

<?php
$pwd1 = 'secret';
$pwd2 = 'Secret';

if (strcmp($pwd1, $pwd2) === 0) { /* 完全相同 (區分大小寫) */ }
if (strcasecmp($pwd1, $pwd2) === 0) { /* 不區分大小寫相同 */ }

// 密碼驗證請用 password_verify()
?>

9. 換行符轉 <br> (nl2br)

<?php
$comment = "Line 1\nLine 2\r\nLine 3";
echo nl2br($comment);
// Line 1
\nLine 2
\nLine 3 ?>

10. 自動換行 (wordwrap)

<?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)
長度strlenmb_strlen
截取substrmb_substr
位置strposmb_strpos
替換str_replacemb_str_replace (PHP 8+)
分割explodemb_split / preg_split
比較strcmpmb_strcmp / Collator
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved