You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将标题前的锚点图标移至标题后?PHP函数修改求助

解决锚点图标移至标题后方的问题

你的代码当前是在标题内容的起始位置插入锚点图标,所以图标会显示在标题文字前方。要将图标移到标题后方,只需调整插入位置到标题内容的末尾即可,修改后的代码如下:

public static function add_anchors($text)
{
    // Search for headlines.
    $pattern = '#<h([1-6])(?: [^>]+)?>(.+?)</h\1>#is';
    preg_match_all($pattern, $text, $headlines, PREG_OFFSET_CAPTURE);

    $offset = 0;

    if ($headlines) {
        foreach ($headlines[2] as $match) {
            list($headline, $pos) = $match;

            if (strlen($headline)) {
                $anchor = \sanitize_title($headline);
                $icon = '<a href="#' . $anchor . '" aria-hidden="true" class="aal_anchor" id="' . $anchor . '"><svg aria-hidden="true" class="aal_svg" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg></a>';

                // 插入到标题内容末尾、闭合标签之前
                $text = substr_replace($text, $icon, $offset + $pos + strlen($headline), 0);
                $offset += strlen($icon);
            }
        }
    }

    return $text;
}

修改说明

  • 核心调整:将插入位置从$offset + $pos改为$offset + $pos + strlen($headline),这样锚点图标会被插入到标题文字的最后面,也就是<hX>标签的闭合标签</hX>之前
  • 更新了注释,明确当前插入位置的逻辑

内容的提问来源于stack exchange,提问作者user7415742

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 09:51:28