如何获得最后一个字的索引以大写字母在PHP
考虑到这一输入字符串:如何获得最后一个字的索引以大写字母在PHP
“这是一个测试字符串获取单词的最后一个索引在PHP中的大写字母”
我怎样才能得到最后的大写字母的位置(在这个例子中,第一个“P”(不是最后一个“PHP”字的“P”)?
的位置,我认为这正则表达式请试试看。
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;
如果您还需要考虑一个非正则表达式的版本:您可以尝试在空白字符分割字符串,迭代返回结果字符串数组,并检查当前字符串的第一个字符是否为大写字符,如下所示(您可能想要添加索引/空值检查):
<?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
的索引。
安地列斯的格局看起来非常稳固,但这会发现位置更快...
.* \K[A-Z]{2,}
下面是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-z
和rtrim()
,然后找到最右侧的空间,并将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
你说“我可以得到最后一个大写字母的位置”,在括号中提到了不是最后一个大写字母的“PHP”字的第一个“P”。那么你真的需要什么?此外,你有没有尝试过分享? –
这似乎工作https://regex101.com/r/KkJeho/1 – Andreas
等等..你是什么意思的位置?就像你从strpos中得到的字符数?你为什么要标记这个正则表达式?正则表达式不会给你一个计数 – Andreas