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

如何用preg_replace仅替换自有域名下的PDF链接路径与文件名

解决方案

正则替换方案(适合简单HTML场景)

使用preg_replace精准匹配example.com域名下/documents/en/路径的PDF链接,避免误修改其他域名的链接。代码如下:

if($_COOKIE['googtrans'] == "/en/es") {
    // 匹配example.com下/documents/en/的PDF链接,忽略大小写
    $pattern = '/(https:\/\/example\.com\/documents\/en\/)([^"\.]+\.)pdf/i';
    $replacement = 'https://example.com/documents/es/$1_SPANISH.pdf';
    $text = preg_replace($pattern, $replacement, $text);
}

正则说明

  • /i:忽略大小写,可匹配.pdf、.PDF等不同大小写的后缀
  • https:\/\/example\.com\/documents\/en\/:精准锁定自有域名下的目标路径,转义/和.等正则特殊字符
  • ([^"\.]+\.):捕获文件名主体和后缀前的点(比如whatever.),确保只匹配到当前链接内的文件名,不会跨标签匹配
  • 替换后的$1对应捕获的文件名部分,自动拼接_SPANISH后缀并替换路径中的en为es

DOMDocument方案(更可靠的HTML处理)

如果页面HTML结构复杂,正则可能出现匹配异常,建议用DOM解析来精准定位a标签并修改:

if($_COOKIE['googtrans'] == "/en/es") {
    $dom = new DOMDocument();
    // 忽略HTML解析错误,兼容不规范的页面代码
    libxml_use_internal_errors(true);
    $dom->loadHTML($text);
    libxml_clear_errors();

    $xpath = new DOMXPath($dom);
    // 筛选所有href包含example.com/documents/en/且后缀为pdf的a标签
    $links = $xpath->query('//a[contains(@href, "https://example.com/documents/en/") and (ends-with(@href, ".pdf") or ends-with(@href, ".PDF"))]');

    foreach ($links as $link) {
        $oldHref = $link->getAttribute('href');
        // 替换路径中的en为es
        $newHref = str_replace('/documents/en/', '/documents/es/', $oldHref);
        // 在文件名后缀前添加_SPANISH
        $newHref = preg_replace('/(\.pdf)$/i', '_SPANISH$1', $newHref);
        // 更新href属性和链接文本
        $link->setAttribute('href', $newHref);
        $link->nodeValue = $newHref;
    }

    // 转换回HTML字符串
    $text = $dom->saveHTML();
}

优势

  • 精准定位a标签,避免正则误匹配非链接文本中的相似字符串
  • 兼容各种HTML结构,不会因为标签嵌套或属性顺序问题失效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 17:37:03