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

北战南征 提交于 2020-06-02 06:30:56

问题


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


回答1:


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.




回答2:


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...)



回答3:


Nicholas and Bernhard have provided successful regex patterns but they are not as efficient as they could be.

Use /[^A-Z]+/ and an empty replacement string with preg_replace().

The negated character class has a one or more quantifier, so longer substrings are matched and fewer replacements are required.


This is the best pattern to use with preg_split as well, but preg_split generates an array, so there is the extra step of calling implode.




回答4:


I've got a more complicated solution but it works too!

$s = str_split("Social Inc.");
foreach ($s as $idx => $char) {
    if(preg_match("/[A-Z]/", $char))
    {
        echo $char;
    }
}

It will echo the upper-case letters.




回答5:


You can use preg_split php function too with regx

$pieces = preg_split('/(?=[A-Z])/',$str);



回答6:


Here is what you need to do:

$str = explode(' ', $ster);
$newStr = strtoupper($str[0][0] . $str[1][0]);


来源:https://stackoverflow.com/questions/44950173/how-to-remove-all-non-uppercase-characters-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!