Search code examples
phpregexregular-language

PHP regex add slashes before upper case leter


Before: ThisIsExample After: This-Is-Example

It's possible do with regular expression ? I try do this by exploding by upper case letter but it's impossible devide string by upper case leteer.


Solution

  • You can do it like this:

    $result = preg_replace('~[a-z]\K(?=[A-Z])~', '-', $yourString);
    

    \K reset all that have been matched before, then you can with this trick match all uppercase preceded by a lowercase.

    (?=..) is a lookahead and means followed by. A lookahead is just a check but match nothing.