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:

JavaScript

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:

JavaScript

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