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

PHP正则替换href中的URL并集成本地化函数的问题

Got it, let's fix this for you! The issue here is that plain preg_replace with a string replacement can't run a custom function on each matched URL—you need to use preg_replace_callback instead, which lets you execute code for every match.

Here's how to adjust your code to integrate your localization function:

First, let's recap your core goal: you want to grab every URL inside href attributes, run it through your localization function, then put the processed URL back into the text.

Let's assume your localization function is named localize_url (swap this with your actual function name). Here's the modified code:

$text = "this is a test text blabla <a href=\"https://example.com/test/\">Test</a>";
// Cleaned up your regex (removed the unnecessary trailing +)
$pattern = "/(?<=href=(\"|'))[^\"']+(?=(\"|'))/";

// Example localization function (replace this with your actual logic)
function localize_url($originalUrl) {
    // For demo: swap example.com with a localized domain
    return str_replace('example.com', 'local.example.com', $originalUrl);
}

// Use preg_replace_callback to process each matched URL
$updatedText = preg_replace_callback($pattern, function($matches) {
    // $matches[0] holds the full URL we captured
    return localize_url($matches[0]);
}, $text);

echo $updatedText;

Key details to note:

  • preg_replace_callback replaces each match with the return value of your callback function. This is exactly what you need to run your localization logic per URL.
  • I trimmed the trailing + from your regex—[^\"']+ already matches one or more non-quote characters, so the extra + was redundant and could cause unexpected matching behavior.
  • If your localization function needs additional parameters (like a locale code), you can pass them into the callback using the use keyword:
    $targetLocale = 'de_DE';
    $updatedText = preg_replace_callback($pattern, function($matches) use ($targetLocale) {
        return localize_url($matches[0], $targetLocale);
    }, $text);
    

This setup will seamlessly apply your URL localization to every href link in your text.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 10:08:13