如何删除字符串中的所有非大写字符? [英] How to remove all non-uppercase characters in a string?

查看:37
本文介绍了如何删除字符串中的所有非大写字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是的,我基本上只是想把像 Social Inc.David Jason 之类的短语分解为 SIDJ.我试过使用explode但不知道如何爆炸所有BUT大写字母,我需要使用preg_match()吗?

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

推荐答案

你可以使用这个正则表达式 (?![AZ]).preg_replace() 来替换除大写字符外的所有字符.

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

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

正则表达式将查找任何不是大写字母(?! 否定前瞻).
如果你想用其他情况测试它,我已经创建了一个 regex101.

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 作为此线程的更新,您还可以使用方括号内的 ^ 字符来反转效果.

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.

这篇关于如何删除字符串中的所有非大写字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆