Search code examples
phpregexcapitalizeucfirst

Regex in PHP to find last upcase char from the Camel Case


I want to match in PHP the last capitalize (http://php.net/manual/en/function.ucfirst.php) character in the string.

To add to the complication I want to ignore everything after a different string, e.g. a sequence of uppercases that not capitalized or in camel case style.

Here follow some examples of what should and shouldnt match

Matches:

Foobar => Expected char: F
fooBar  => Expected char: B
A_fooBar  => Expected char: B
fooBAR => Expected char: B (Most complicated situation)

No matches:

foo A_bar
foobar
foo bar foo bar
foobar /* Comment */

So far I've tried the following regex:

(?!A_)[A-Z](?!((?!/\*).)*\*/)

but with no luck. From Question: the Regexp match any uppercase characters except a particular string (Very similar situation)

@edit

And another regex

/([A-Z])[^A-Z\W]*$/

http://phpfiddle.org/main/code/dyq-3h7


Solution

  • I believe this matches where appropriate, and will ignore your other examples as well.

    ^\w*?(?<![A-Z_])([A-Z])(?!_)
    

    See this fiddle