Skip to content
Advertisement

Replacing spaces in regular expression-match with underscores

I want the link destination to have underscores instead of spaces between the words in the link address.

My code looks like:

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

The first occurance of $1 should have underscores instead of spaces.

Thank you!

Advertisement

Answer

You may use preg_replace_callback since you may not manipulate the backreferences in the preg_replace string replacement patterns:

$text = "[[Some text]] and [[one more here]]";
echo preg_replace_callback("/[[(.+?)]]/", function($m) {
        return '<a href="/XLab/?document=' . str_replace(' ', '_', $m[1]) . '">' . $m[1] . '</a>';
    }, $text);

See the PHP demo.

Here,

  • $m is the match object containing $m[0], the whole match, and $m[1], the contents between [[ and ]]
  • str_replace(' ', '_', $m[1]) replaces each space with _. Replace with preg_replace('~s+~u', '_', $m[1]) to replace any 1+ whitespace chunks with a single _.
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement