简体   繁体   中英

How to get the index of last word with an uppercase letter in PHP

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?

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

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 prints 80 which is indeed the index of the first P in PHP (including whitespaces).

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

.* \K[A-Z]{2,}

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('/.* \K[A-Z]{2,}/',$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 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[AZ]/

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 az and a space with rtrim() then finding the right-most space, and adding 1 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM