Skip to content
Advertisement

Placing a dash for each identical word (regex, php)

Please tell me if it is possible to make a search for all identical words through rejax and insert a dash between them until such a word is no longer the next in the sentence.

Example here: https://regex101.com/r/1GQiQ8/2

My regex:

JavaScript

Sample text:

JavaScript

How it should be:

JavaScript

How does it work now:

JavaScript

Advertisement

Answer

You can use

JavaScript

Replace with -. See the regex demo.

If the words must be identical use 1 instead of (?1):

JavaScript

See this regex demo

Details

  • b(long|anyword)b – Group 1: either of two words, as a whole word
  • K – match reset operator, it removes all text matched so far from the match memory buffer
  • [- ] – either a hyphen or space
  • (?=(?:(?1))b) – a positive lookahead that matches a location immediately followed with a whole long or anyword word.
  • (?=1b) – a positive lookahead that matches a location immediately followed with the string captured in Group 1 as a whole word.
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement