如何在PHP中使用大写字母获取最后一个单词的索引

use*_*801 0 php regex substring offset uppercase

考虑以下输入字符串:

“这是一个测试字符串,用于获取PHP中带有大写字母的单词的最后一个索引”

如何获取“ PHP”单词的最后一个大写字母的位置(在本示例中为第一个“ P”(而不是最后一个“ P”)的位置)?

And*_*eas 5

我认为此正则表达式有效。试试看。

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

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

编辑以解决Wiktor在注释中写的内容,我认为您可以str_replace所有新行,并用空格作为正则表达式中的输入字符串。
这应该使正则表达式将其视为单行正则表达式,并仍然给出正确的输出。
虽然没有测试。

要查找字母/单词的位置:

$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;
Run Code Online (Sandbox Code Playgroud)

https://3v4l.org/sJilv