PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 20, 2022

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

 November 20, 2022     php, preg-replace, regex, uppercase     No comments   

Issue

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.



Answered By - Nicolas
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing