Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()?

like image 673
Martin Dev Avatar asked Nov 22 '25 09:11

Martin Dev


2 Answers

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.

like image 134
Nicolas Avatar answered Nov 24 '25 00:11

Nicolas


Quick and easy:

$ucaseletters = preg_replace('/[^A-Z]/', '', $input);

This will replace everything that is not an uppercase Letter within the Range A-Z.

Explanation:

^ within [] (Character-Set) is the negation-Operator (=anything that is NOT...)
like image 21
Bernhard Avatar answered Nov 23 '25 23:11

Bernhard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!