如何获得最后一个字的索引以大写字母在PHP

问题描述:

考虑到这一输入字符串:如何获得最后一个字的索引以大写字母在PHP

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

我怎样才能得到最后的大写字母的位置(在这个例子中,第一个“P”(不是最后一个“PHP”字的“P”)?

+0

你说“我可以得到最后一个大写字母的位置”,在括号中提到了不是最后一个大写字母的“PHP”字的第一个“P”。那么你真的需要什么?此外,你有没有尝试过分享? –

+0

这似乎工作https://regex101.com/r/KkJeho/1 – Andreas

+0

等等..你是什么意思的位置?就像你从strpos中得到的字符数?你为什么要标记这个正则表达式?正则表达式不会给你一个计数 – Andreas

的位置,我认为这正则表达式请试试看。

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

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

编辑解决什么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; 

https://3v4l.org/sJilv

+0

'“/.* \ s([A-Z])/”'将起作用,除非该字符串是多行的,并且最后一个大写的*字不在第一行。或者,如果大写的单词前面加上了空格以外的非单词字符。顺便说一句,不OP只想匹配ALLCAPS单词? –

+0

@Wiktor true。但我不知道OP想要什么。他还说“职位”,这使得reges或多或少无用。 – Andreas

+0

@Wiktor我想我已经解决了你的两个担忧:-) – Andreas

如果您还需要考虑一个非正则表达式的版本:您可以尝试在空白字符分割字符串,迭代返回结果字符串数组,并检查当前字符串的第一个字符是否为大写字符,如下所示(您可能想要添加索引/空值检查):

<?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--; 
} 

这将打印80这确实是PHP(包括空格)中第一个P的索引。

+1

我觉得这是一个很好的答案。为什么它低调?它实际上给了我的位置,而我没有。这是免费的正则表达式(除非它是一个高字符串)可能使它更快。来自我的+1! – Andreas

+0

我猜是因为这个问题实际上被标记为正则表达式..但谢谢! :) – eol

+0

OP在我看来并不决定方法。如果是这样的话,那么会有数百个线程在解析html时使用正则表达式的答案。但没有。 – Andreas

安地列斯的格局看起来非常稳固,但这会发现位置更快...

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

Pattern Demo

下面是PHP实现:Demo

​​

如果你想看到一个精简的非正则表达式方法,这将会工作:

代码: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)); 

输出:

Position = 80 

这假定有输入字符串的全部大写的单词。如果有可能没有全部大写的单词,那么一个条件将会把它整理出来。


编辑,重新阅读的问题后,我不确定是什么让PHP目标串 - 无论它是因为它是全部大写,或者只是最后一个字开始一个大写字母。

如果只是最后一个字开头的大写字母那么这种格局将做到:/.* \K[A-Z]/

如果字必须全部大写,则有可能是/b单词边界可能是必要的。

一些更多的样本和说明从OP将是有益的。


另一个编辑,你可以声明一组字符来排除和使用两个字符串函数。我使用a-zrtrim(),然后找到最右侧的空间,并将1添加到它。

$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