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

如何利用短链功能替换邮件链接?preg_replace赋值失败求助

The problem with preg_replace here is that it can't dynamically execute your Shorten function for each matched URL to generate the replacement. Instead, you'll want to use preg_replace_callback, which lets you run a custom function on every match and return the modified content.

Here's how to implement it step by step:

  1. Keep your existing Shorten function (I’ll include it for context, plus a small improvement):
function Shorten($url){ 
    $api_url="https://server/api?api=key&url=".$url."&format=text"; 
    $res= @file_get_contents($api_url); 
    if($res){ 
        return $res; 
    }
    // Fallback to original URL if API fails (prevents broken links)
    return $url;
}
  1. Use preg_replace_callback to process your email HTML:
// Your original email HTML content
$emailHtml = 'Hey! Go in <a href="http://google.com">Google</a> or <a href="http://yahoo.com">Yahoo</a>';

// Process the HTML to replace all links with shortened versions
$modifiedHtml = preg_replace_callback(
    '/<a href="([^"]+)">(.*?)<\/a>/i',
    function($match) {
        // $match[1] = the original URL from href
        // $match[2] = the visible link text
        $shortUrl = Shorten($match[1]);
        // Return the updated anchor tag with shortened URL
        return '<a href="' . htmlspecialchars($shortUrl) . '">' . $match[2] . '</a>';
    },
    $emailHtml
);

// Example: Output or use the modified HTML
echo $modifiedHtml;

How this works:

  • The regex /<a href="([^"]+)">(.*?)<\/a>/i matches anchor tags, capturing the target URL as $match[1] and the link text as $match[2].
  • The anonymous callback function runs for every matched link: it calls your Shorten function on the original URL, then returns a new anchor tag with the shortened URL.
  • htmlspecialchars ensures any special characters in the shortened URL are properly escaped, so your HTML stays valid.

Quick adjustments for edge cases:

  • If your email uses single quotes for href attributes, tweak the regex to /<a href='([^']+)'>(.*?)<\/a>/i.
  • If you need to handle links with query parameters or special characters, the regex will still work since it captures everything inside the quotes.

内容的提问来源于stack exchange,提问作者graf-8269

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:09:37