Search code examples
phpregexwordschars

PHP Regular expression to get words with repeated chars in a string


I'm trying to get the words in a string with repeated chars. For example: "II loooovve this video. It's awesooooommeee."

How can I get the result: loooovve awesooooommeee ?


Solution

  • You can use this regex with a back-reference:

    \b\w*(\w)\1\w*
    

    RegEx Demo

    RegEx Breakup:

    \b     # word boundary
    \w*    # match 0 or more word characters
    (\w)   # match a single word char and capture it as group #1
    \1     # back-reference to captured group #1 to make sure we have a *repeat*
    \w*    # match 0 or more word characters
    

    btw it will also match II since it has a repeating character I.