strrpos() - 计算指定字符串在目标字符串中最后一次出现的位置 - php 字符串函数
strrpos()
(PHP 4, PHP 5, PHP 7)
计算指定字符串在目标字符串中最后一次出现的位置
说明
strrpos(string $haystack, string $needle[,int $offset= 0] ): int返回字符串$haystack中$needle最后一次出现的数字位置。注意 PHP4 中,needle 只能为单个字符。如果 needle 被指定为一个字符串,那么将仅使用第一个字符。
参数
$haystack在此字符串中进行查找。
$needle如果$needle不是一个字符串,它将被转换为整型并被视为字符的顺序值。
$offset或许会查找字符串中任意长度的子字符串。负数值将导致查找在字符串结尾处开始的计数位置处结束。
返回值
返回 needle 存在的位置。如果没有找到,返回FALSE
。 Also note that string positions start at 0, and not 1.
ReturnsFALSE
if the needle was not found.
此函数可能返回布尔值FALSE
,但也可能返回等同于FALSE
的非布尔值。请阅读布尔类型章节以获取更多信息。应使用===运算符来测试此函数的返回值。
更新日志
版本 | 说明 |
---|---|
5.0.0 | 参数$needle可以是一个多字符的字符串。 |
5.0.0 | 引入$offset参数。 |
范例
检查字串是否存在
很容易将“在位置 0 处找到”和“未发现字符串”这两种情况搞错。这是检测区别的办法:
使用偏移位置进行查找
参见
strpos()
查找字符串首次出现的位置stripos()
查找字符串首次出现的位置(不区分大小写)strripos()
计算指定字符串在目标字符串中最后一次出现的位置(不区分大小写)strrchr()
查找指定字符在字符串中的最后一次出现substr()
返回字符串的子串
The documentation for 'offset' is misleading. It says, "offset may be specified to begin searching an arbitrary number of characters into the string. Negative values will stop searching at an arbitrary point prior to the end of the string." This is confusing if you think of strrpos as starting at the end of the string and working backwards. A better way to think of offset is: - If offset is positive, then strrpos only operates on the part of the string from offset to the end. This will usually have the same results as not specifying an offset, unless the only occurences of needle are before offset (in which case specifying the offset won't find the needle). - If offset is negative, then strrpos only operates on that many characters at the end of the string. If the needle is farther away from the end of the string, it won't be found. If, for example, you want to find the last space in a string before the 50th character, you'll need to do something like this: strrpos($text, " ", -(strlen($text) - 50)); If instead you used strrpos($text, " ", 50), then you would find the last space between the 50th character and the end of the string, which may not have been what you were intending.
Ten years on, Brian's note is still a good overview of how offsets work, but a shorter and simpler summary is: strrpos($x, $y, 50); // 1: this tells strrpos() when to STOP, counting from the START of $x strrpos($x, $y, -50); // 2: this tells strrpos() when to START, counting from the END of $x Or to put it another way, a positive number lets you search the rightmost section of the string, while a negative number lets you search the leftmost section of the string. Both these variations are useful, but picking the wrong one can cause some highly confusing results!
Here is a simple function to find the position of the next occurrence of needle in haystack, but searching backwards (lastIndexOf type function): //search backwards for needle in haystack, and return its position function rstrpos ($haystack, $needle, $offset){ $size = strlen ($haystack); $pos = strpos (strrev($haystack), $needle, $size - $offset); if ($pos === false) return false; return $size - $pos; } Note: supports full strings as needle
RE: hao2lian There are a lot of alternative - and unfortunately buggy - implementations of strrpos() (or last_index_of as it was called) on this page. This one is a slight modifiaction of the one below, but it should world like a *real* strrpos(), because it returns false if there is no needle in the haystack.
The description of offset is wrong. Here’s how it works, with supporting examples. Offset effects both the starting point and stopping point of the search. The direction is always right to left. (The description wrongly says PHP searches left to right when offset is positive.) Here’s how it works: When offset is positive, PHP searches right to left from the end of haystack to offset. This ignores the left side of haystack. When offset is negative, PHP searches right to left, starting offset bytes from the end, to the start of haystack. This ignores the right side of haystack. Example 1: $foo = ‘aaaaaaaaaa’; var_dump(strrpos($foo, 'a', 5)); Result: int(10) Example 2: $foo = "aaaaaa67890"; var_dump(strrpos($foo, 'a', 5)); Result: int(5) Conclusion: When offset is positive, PHP searches right to left from the end of haystack. Example 3: $foo = "aaaaa567890"; var_dump(strrpos($foo, 'a', 5)); Result: bool(false) Conclusion: When offset is positive, PHP stops searching at offset. Example 4: $foo = ‘aaaaaaaaaa’; var_dump(strrpos($foo, 'a', -5)); Result: int(6) Conclusion: When offset is negative, PHP searches right to left, starting offset bytes from the end. Example 5: $foo = "a234567890"; var_dump(strrpos($foo, 'a', -5)); Result: int(0) Conclusion: When offset is negative, PHP searches right to left, all the way to the start of haystack.
Returns the filename's string extension, else if no extension found returns false. Example: filename_extension('some_file.mp3'); // mp3 Faster than the pathinfo() analogue in two times.
I was immediatley pissed when i found the behaviour of strrpos ( shouldnt it be called charrpos ?) the way it is, so i made my own implement to search for strings.
$offset is very misleading, here is my understanding: function mystrrpos($haystack, $needle, $offset = 0) { if ($offset == 0) { return strrpos ($haystack, $needle); } else { return strrpos (substr($haystack, 0, $offset), $needle); } }
This seems to behave like the exact equivalent to the PHP 5 offset parameter for a PHP 4 version.
I've got a simple method of performing a reverse strpos which may be of use. This version I have treats the offset very simply: Positive offsets search backwards from the supplied string index. Negative offsets search backwards from the position of the character that many characters from the end of the string. Here is an example of backwards stepping through instances of a string with this function: Outputs: Test1 11 5 0 Done ---===--- Test2 0 4 With Test2 the first line checks from the first 3 in "12341234" and runs backwards until it finds a 1 (at position 0) The second line checks from the second 2 in "12341234" and seeks towards the beginning for the first 1 it finds (at position 4). This function is useful for php4 and also useful if the offset parameter in the existing strrpos is equally confusing to you as it is for me.
refering to the comment and function about lastIndexOf()... It seemed not to work for me the only reason I could find was the haystack was reversed and the string wasnt therefore it returnt the length of the haystack rather than the position of the last needle... i rewrote it as fallows: this one fallows the strpos syntax rather than java's lastIndexOf. I'm not positive if it takes more resources assigning all of those variables in there but you can put it all in return if you want, i dont care if i crash my server ;). ~SILENT WIND OF DOOM WOOSH!
The "find-last-occurrence-of-a-string" functions suggested here do not allow for a starting offset, so here's one, tried and tested, that does: function my_strrpos($haystack, $needle, $offset=0) { // same as strrpos, except $needle can be a string $strrpos = false; if (is_string($haystack) && is_string($needle) && is_numeric($offset)) { $strlen = strlen($haystack); $strpos = strpos(strrev(substr($haystack, $offset)), strrev($needle)); if (is_numeric($strpos)) { $strrpos = $strlen - $strpos - strlen($needle); } } return $strrpos; }
Maybe I'm the only one who's bothered by it, but it really bugs me when the last line in a paragraph is a single word. Here's an example to explain what I don't like: The quick brown fox jumps over the lazy dog. So that's why I wrote this function. In any paragraph that contains more than 1 space (i.e., more than two words), it will replace the last space with ' '. So, it would change "The quick brown fox jumps over the lazy dog." to "The quick brown fox jumps over the lazy dog." That way, the last two words will always stay together.
i wanted to find a leading space BEFORE a hyphen Crude Oil (Dec) 51.00-56.00 so I had to find the position of the hyphen then subtract that position from the length of the string (to make it a negative number) and then walk left toward the beginning of the string, looking for the first space before the hyphen ex: $str_position_hyphen = strpos($line_new,"-",$str_position_spread); $line_new_length = strlen($line_new); $str_position_hyphen_from_end = $str_position_hyphen - $line_new_length; echo "hyphen position from end = " . $str_position_hyphen_from_end . "
\n"; $str_position_space_before_hyphen = strrpos($line_new, " ", $str_position_hyphen_from_end); echo "*** previous space= " . $str_position_space_before_hyphen . "
\n"; $line_new = substr_replace($line_new, ",", $str_position_space_before_hyphen, 1 ); echo $line_new . "
\n";
I should have looked here first, but instead I wrote my own version of strrpos that supports searching for entire strings, rather than individual characters. This is a recursive function. I have not tested to see if it is more or less efficient than the others on the page. I hope this helps someone!
I needed to check if a variable that contains a generated folder name based on user input had a trailing slash. This did the trick:
Very handy to get a file extension: $this->data['extension'] = substr($this->data['name'],strrpos($this->data['name'],'.')+1);
Full strpos() functionality, by yours truly. Note that $offset is evaluated from the end of the string. Also note that conforming_strrpos() performs some five times slower than strpos(). Just a thought.
Function to truncate a string Removing dot and comma Adding ... only if a is character found function TruncateString($phrase, $longueurMax = 150) { $phrase = substr(trim($phrase), 0, $longueurMax); $pos = strrpos($phrase, " "); $phrase = substr($phrase, 0, $pos); if ((substr($phrase,-1,1) == ",") or (substr($phrase,-1,1) == ".")) { $phrase = substr($phrase,0,-1); } if ($pos === false) { $phrase = $phrase; } else { $phrase = $phrase . "..."; } return $phrase; }
If you wish to look for the last occurrence of a STRING in a string (instead of a single character) and don't have mb_strrpos working, try this: function lastIndexOf($haystack, $needle) { $index = strpos(strrev($haystack), strrev($needle)); $index = strlen($haystack) - strlen(index) - $index; return $index; }
Function like the 5.0 version of strrpos for 4.x. This will return the *last* occurence of a string within a string. function strepos($haystack, $needle, $offset=0) { $pos_rule = ($offset
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!
内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)