萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 自動補全網址協定並轉換為可點擊超連結

兩大需求

  1. 使用者輸入 example.com → 自動補齊 https://example.com
  2. 文字中的網址/Email → 自動轉為 <a href=...>

函式一:補全協定

<?php
function ensureScheme(string $url, string $defaultScheme = 'https'): string
{
    $url = trim($url);
    if ($url === '') return '';
    // 已有協定
    if (preg_match('#^[a-z][a-z0-9+.-]*://#i', $url)) return $url;
    // 類似 domain/path 或 IP:port
    return $defaultScheme . '://' . $url;
}

// 測試
var_dump(ensureScheme('example.com'));           // https://example.com
var_dump(ensureScheme('https://example.com'));    // https://example.com (保持)
var_dump(ensureScheme('ftp://files.example.com'));// ftp://files.example.com (保持)
?>

函式二:文字轉超連結(改良版)

<?php
function autoLink(string $text, array $options = []): string
{
    $opts = array_merge([
        'target'      => '_blank',
        'rel'         => 'noopener noreferrer',
        'maxLength'   => 60,      // 顯示文字截斷長度
        'class'       => 'auto-link',
    ], $options);

    $attr = sprintf('class="%s" target="%s" rel="%s"',
        htmlspecialchars($opts['class']),
        htmlspecialchars($opts['target']),
        htmlspecialchars($opts['rel'])
    );

    // 1. 先處理已有標籤的情況(避免雙重包裹)——簡易:略過  內容
    // 這裡用簡單策略:先轉換 URL,再轉 Email,最後截斷顯示文字

    // URL (http/https/ftp/ftps)
    $text = preg_replace_callback(
        '#\b((?:https?|ftps?)://[^\s<>"\']+)#i',
        function($m) use ($attr, $opts) {
            $url = $m[1];
            $display = strlen($url) > $opts['maxLength']
                ? substr($url, 0, $opts['maxLength']) . '…'
                : $url;
            return "$display";
        },
        $text
    );

    // 裸域名/子域名 (example.com/path) —— 較激進,可選啟用
    // $text = preg_replace_callback('#(?])\b([a-z0-9-]+\.[a-z]{2,}(?:/[^\s<>"\']*)?)#i', ...);

    // Email
    $text = preg_replace_callback(
        '#\b([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,})\b#',
        function($m) use ($attr) {
            return "{$m[1]}";
        },
        $text
    );

    return $text;
}

// 使用
$input = '請訪問 example.com 或 https://php.net 聯繫 admin@example.com';
echo autoLink($input);

整合使用流程

$userInput = 'www.example.com/path?query=1';
$url = ensureScheme($userInput);          // https://www.example.com/path?query=1
$html = autoLink($url);                   // https://www.example.com/path?query=1

安全提醒

  • **輸出時務必 htmlspecialchars()** 所有動態屬性值,防 XSS
  • **rel="noopener noreferrer"** 防止 window.opener 洩露
  • **不信任使用者輸入的 target/_blank**,由伺服器端固定輸出
  • 大量文字處理時,考慮效能:單次 preg_replace_callback 處理所有模式
copyright © 萬盛學電腦網 all rights reserved