Search code examples
phpregexpreg-replaceuppercase

How to remove all non-uppercase characters in a string?


Yeah I'm basically just trying to explode a phrase like Social Inc. or David Jason to SI and DJ. I've tried using explode but couldn't figure out how to explode everything BUT the capital letters, do I need to use preg_match()?


Solution

  • You can use this regex (?![A-Z]). with preg_replace() to replace every char except the one in uppercase.

    preg_replace("/(?![A-Z])./", "", $yourvariable)
    

    The regex will look for anythings NOT an uppercase letter ( ?! negative lookahead ).
    I've created a regex101 if you wish to test it with other cases.

    EDIT As an update of this thread, You could also use the ^ char inside the square braquets to reverse the effect.

    preg_replace("/([^A-Z])./", "", $yourvariable)
    

    This will match all char that are not uppercase and replace them with nothing.