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

Web 開發者必備 10 個救命 PHP 代碼片段:高亮、訂閱、密碼、CSS、短網址、年齡、計時、維護、緩存、序數

     編輯:PHP 相關知識

這 10 個片段覆蓋搜索、營運、安全、前端、工具、運維六大高頻場景,複製即用,解決 80% 臨時需求。

1. 關鍵詞高亮 (搜索結果標紅)

function highlight(string $text, array $keywords): string {
    if (empty($keywords) || $text === '') return $text;
    $pattern = '/\b(' . implode('|', array_map('preg_quote', $keywords)) . ')\b/i';
    return preg_replace($pattern, '<mark>$1</mark>', $text);
}

2. Feedburner 平均訂閱數 (7 天)

function get_feedburner_avg(string $feedId, int $days = 7): int {
    $today = date('Y-m-d');
    $ago   = date('Y-m-d', strtotime("-$days days"));
    $url   = "https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=$feedId&dates=$ago,$today";
    $xml   = simplexml_load_string(file_get_contents($url));
    $total = 0;
    foreach ($xml->feed->entry as $entry) {
        $total += (int)$entry['circulation'];
    }
    return round($total / $days);
}

3. 安全隨機密碼生成 (可控強度 0-8)

function generatePassword(int $length = 12, int $strength = 4): string {
    $vowels = 'aeuy';
    $cons   = 'bdghjmnpqrstvz';
    if ($strength >= 1) $cons .= 'BDGHJLMNPQRSTVWXZ';
    if ($strength >= 2) $vowels .= 'AEUY';
    if ($strength >= 4) $cons .= '23456789';
    if ($strength >= 8) $vowels .= '@#$%';

    $pool = $vowels . $cons;
    $pwd  = '';
    for ($i = 0; $i < $length; $i++) {
        $pwd .= $pool[random_int(0, strlen($pool) - 1)];
    }
    return $pwd;
}

4. 多 CSS 合併壓縮輸出 (現代寫法)

header('Content-Type: text/css; charset=utf-8');

function compress_css(string $css): string {
    $css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css); // 移除註釋
    $css = preg_replace('/\s+/', ' ', $css); // 壓縮空白
    return trim($css);
}

$files = ['css/reset.css', 'css/layout.css', 'css/theme.css', 'css/print.css'];
$output = '';
foreach ($files as $file) {
    if (is_readable($file)) $output .= file_get_contents($file);
}
echo compress_css($output);

5. 短網址生成 (TinyURL API)

function getTinyUrl(string $url): string {
    return file_get_contents("https://tinyurl.com/api-create.php?url=" . urlencode($url));
}

6. 生日計算年齡 (精確到天)

function ageFromBirthdate(string $birthdate): int {
    $birth = strtotime($birthdate);
    if ($birth === false) return 0;
    $today = time();
    $years = date('Y', $today) - date('Y', $birth);
    $mdToday  = date('md', $today);
    $mdBirth  = date('md', $birth);
    if ($mdToday < $mdBirth) $years--;
    return $years;
}

7. 代碼執行時間計測 (微秒級)

$start = hrtime(true); // PHP 7.3+ 高精度
// 你的業務代碼
$end   = hrtime(true);
echo 'Execution time: ' . (($end - $start) / 1e9) . ' seconds';

8. 維護模式中間件 (優雅降級)

function maintenanceMode(bool $enable = true): void {
    $maintenanceFile = __DIR__ . '/maintenance.php';
    $isMaintenance   = basename($_SERVER['SCRIPT_FILENAME']) === 'maintenance.php';

    if ($enable && !$isMaintenance) {
        header('Location: /maintenance.php', true, 503);
        exit;
    }
    if (!$enable && $isMaintenance) {
        header('Location: /', true, 302);
        exit;
    }
}

// 入口文件最早調用
maintenanceMode(true); // 開啟維護
// maintenanceMode(false); // 關閉維護

9. 靜態資源防緩存 (時間戳版本號)

<link href="/css/app.css?v=<?= time() ?>" rel="stylesheet">
<script src="/js/app.js?v=<?= time() ?>"></script>

// 生產環境建議用文件哈希/構建版本號替代 time()
// <link href="/css/app.css?v=<?= filemtime('public/css/app.css') ?>">

10. 數字轉英文序數 (1st, 2nd, 3rd, 4th...)

function toOrdinal(int $num): string {
    $lastTwo = $num % 100;
    if ($lastTwo >= 11 && $lastTwo <= 13) return $num . 'th';
    switch ($num % 10) {
        case 1: return $num . 'st';
        case 2: return $num . 'nd';
        case 3: return $num . 'rd';
        default: return $num . 'th';
    }
}

使用建議

  • 放入 app/Helpers/Functions.php,composer.json autoload.files 載入。
  • 涉及外部 API (Feedburner、TinyURL) 必加超時、重試、降級邏輯。
  • 密碼生成、高亮等用戶可見功能需前端配合樣式 (如 mark { background: #ff0; })。
  • 維護模式建議配合 Nginx error_page 503 /maintenance.html 靜態頁,完全繞過 PHP。

這 10 個片段,是每個 PHP 開發者工具箱裡的「創可貼」——小傷小痛,貼上即愈,專注核心業務。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved