爱好其实是一种惩罚
纪念我的放肆-消失的那么快
返回顶部
当前位置:首页 > 教学教程 > 正文

emlog自动将文章中的URL转换为可点击链接

作者:冲灵 发布时间:2025-09-04 21:43 分类: 教学教程 浏览:24 评论:0


导读:在文章内容页的代码部分(大约在文件中间位置),找到这行代码: <div class="tx-text f-16 mb15"> <?= $log_conte...

在文章内容页的代码部分(大约在文件中间位置),找到这行代码:

<div class="tx-text f-16 mb15">
    <?= $log_content ?>

替换为:

<div class="tx-text f-16 mb15">
    <?= make_clickable($log_content) ?>

然后在文件顶部(<?php 标签之后)添加以下函数定义:

/**
 * 将纯文本URL转换为可点击链接(跳过已链接的URL和图片src)
 */
function make_clickable($text) {
    // 匹配未被<a>标签包裹且不在<img>标签内的http/https/ftp URL
    $text = preg_replace_callback(
        '/(?<!href="|\'>|">|src=")((?:https?|ftp):\/\/[^\s<>"\'\)]+)/i',
        function($matches) {
            return '<a href="'.$matches[1].'" target="_blank" rel="nofollow">'.$matches[1].'</a>';
        },
        $text
    );

    // 匹配未被<a>标签包裹且不在<img>标签内的www开头的URL
    $text = preg_replace_callback(
        '/(?<!href="|\'>|">|src=")(?<!\:\/\/)(www\.[^\s<>"\'\)]+)/i',
        function($matches) {
            return '<a href="http://'.$matches[1].'" target="_blank" rel="nofollow">'.$matches[1].'</a>';
        },
        $text
    );

    // 匹配未被<a>标签包裹且不在<img>标签内的电子邮件
    $text = preg_replace_callback(
        '/(?<!href="|\'>|">|src=")([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})/i',
        function($matches) {
            return '<a href="mailto:'.$matches[1].'">'.$matches[1].'</a>';
        },
        $text
    );

    return $text;
}

功能说明

  1. 1.匹配普通URL​:识别以 http://https:// 或 ftp:// 开头的网址
  2. 2.匹配www开头的URL​:识别以 www. 开头的网址,并自动添加 http://
  3. 3.匹配电子邮件​:识别电子邮件地址并转换为 mailto: 链接
手机扫码阅读

发表评论:

教学教程排行