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?

530

Answer

Solution:

I think this regex works. Give it a try.

https://regex101.com/r/KkJeho/1

$pattern = "/.*\s([A-Z])/";
//$pattern = "/.*\s([A-Z])[A-Z]+/"; pattern to match only all caps word

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:

$str = "this is a Test String to get the last index of word with an uppercase letter in PHP";

$pattern = "/.*\s([A-Z])(\w+)/";
//$pattern = "/.*\s([A-Z])([A-Z]+)/";  pattern to match only all caps word

preg_match($pattern, $str, $match);


$letter = $match[1];
$word = $match[1] . $match[2];
$position = strrpos($str, $match[1].$match[2]);

echo "Letter to find: " . $letter . "\nWord to find: " . $word . "\nPosition of letter: " . $position;

https://3v4l.org/sJilv

235

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

<?php    

$str =  "this is a Test String to get the last index of word with an uppercase letter in PHP";
$explodeStr = explode(" ",$str);
$i = count($explodeStr) - 1;
$characterCount=0;
while($i >= 0) {
    $firstChar = $explodeStr[$i][0];
    if($firstChar == strtoupper($firstChar)){
        echo $explodeStr[$i]. ' at index: ';
        $idx = strlen($str)-strlen($explodeStr[$i] -$characterCount);
        echo $idx;
        break;
    }
    $characterCount += strlen($explodeStr[i]) +1; //+1 for whitespace
    $i--;
} 

This prints80 which is indeed the index of the firstP inPHP (including whitespaces).

426

Answer

Solution:

Andreas' pattern looks pretty solid, but this will find the position faster...

{-code-1}

Pattern Demo

Here is the PHP implementation: Demo

$str='this is a Test String to get the last index of word with an uppercase letter in PHP test';
var_export(preg_match('/{-code-1}/',$str,$out,PREG_OFFSET_CAPTURE)?$out[0][1]:'fail');
// 80

If you want to see a condensed non-regex method, this will work:

Code: Demo

$str='this is a Test String to get the last index of word with an uppercase letter in PHP test';
$allcaps=array_filter(explode(' ',$str),'ctype_upper');
echo "Position = ",strrpos($str,end($allcaps));

Output:

Position = 80

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 makesPHP 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 usinga-z and a space withrtrim() then finding the right-most space, and adding1 to it.

$str='this is a Test String to get the last index of word with an uppercase letter in PHP test';
echo strrpos(rtrim($str,'abcdefghijklmnopqrstuvwxyz '),' ')+1;
// 80

People are also looking for solutions to the problem: xml - How to set Hikvision camera parameters using PHP curl

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.