regex - How to get the index of last word with an uppercase letter in PHP
622
Considering this input string:
"this is a Test String to get the last index of word with an uppercase letter in PHP"
How can I get the position of the last uppercase letter (in this example the position of the first "P" (not the last one "P") of "PHP" word?
Answer
Solution:
I think this regex works. Give it a try.
https://regex101.com/r/KkJeho/1
Edit to solve what Wiktor wrote in comments I think you could str_replace all new lines with space as the input string in the regex.
That should make the regex treat it as a single line regex and still give the correct output.
Not tested though.
To find the position of the letter/word:
https://3v4l.org/sJilv
Answer
Solution:
If you also want to consider a non-regex version: You can try splitting the string at the whitespace character, iterating the resulting string array backwards and checking if the current string's first character is an upper case character, something like this (you may want to add index/null checks):
This prints
80
which is indeed the index of the firstP
inPHP
(including whitespaces).Answer
Solution:
Andreas' pattern looks pretty solid, but this will find the position faster...
Pattern Demo
Here is the PHP implementation: Demo
If you want to see a condensed non-regex method, this will work:
Code: Demo
Output:
This assumes that there is an all caps word in the input string. If there is a possibility of no all-caps words, then a conditional would sort it out.
Edit, after re-reading the question, I am unsure what exactly makes
PHP
the targeted substring -- whether it is because it is all caps, or just the last word to start with a capitalized letter.If just the last word starting with an uppercase letter then this pattern will do:
/.* \K[A-Z]/
If the word needs to be all caps, then it is possible that
/b
word boundaries may be necessary.Some more samples and explanation from the OP would be useful.
Another edit, you can declare a set of characters to exclude and use just two string functions. I am using
a-z
and a space withrtrim()
then finding the right-most space, and adding1
to it.