如何修改preg_replace代码将链接目标的空格替换为下划线?
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:
Recommended: Use preg_replace_callback
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_replaceto 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
Legacy Approach: Using the e Modifier (Not Recommended)
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

