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

如何修改preg_replace代码将链接目标的空格替换为下划线?

Solution to Replace Spaces with Underscores in URL Parameter

Got it, let's sort this out for you! The core requirement here is to keep the original text with spaces in the link display, but replace those spaces with underscores in the document parameter of the URL. Here are two approaches, with the first being the modern, safe recommendation:

This method is the best practice for PHP 5.3+ (all supported versions now) because it avoids security risks associated with older approaches and gives you full control over processing the matched text.

$document->content = preg_replace_callback(
    "/\[\[(.+?)\]\]/",
    function($matches) {
        // Replace spaces with underscores for the URL parameter
        $urlFriendlyText = str_replace(' ', '_', $matches[1]);
        // Build the anchor tag with modified URL and original display text
        return '<a href="/XLab/?document=' . $urlFriendlyText . '">' . $matches[1] . '</a>';
    },
    $document->content
);

How it works:

  • The regex \[\[(.+?)\]\] still captures the text inside double brackets into $matches[1]
  • Inside the callback function, we use str_replace to swap spaces with underscores for the URL parameter
  • The link text stays as the original captured text (with spaces), while the URL uses the underscore version

If you're working with a very old PHP project (pre-7.4) where you can't use preg_replace_callback, you could use the deprecated e modifier. Note: This is unsafe if the captured text contains user input, as it executes PHP code directly.

$document->content = preg_replace(
    "/\[\[(.+?)\]\]/e",
    "'<a href=\"/XLab/?document=' . str_replace(' ', '_', '$1') . '\">$1</a>'",
    $document->content
);

Example Output

For input text like [[My Awesome Document]], both methods will produce:

<a href="/XLab/?document=My_Awesome_Document">My Awesome Document</a>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 17:17:40