我正在使用strrchr函数进行一些测试,但我无法理解输出:
$text = 'This is my code';
echo strrchr($text, 'my');
//my code好的,函数在上次出现之前返回了字符串。
$text = 'This is a test to test code';
echo strrchr($text, 'test');
//t code但是在这种情况下,为什么函数返回"t代码“,而不是”测试代码“呢?
谢谢
发布于 2014-09-28 22:03:39
来自PHP文档
针 如果针包含多个字符,则只使用第一个字符。这种行为不同于strstr()。
因此,您的第一个示例与以下内容完全相同:
$text = 'This is my code';
echo strrchr($text, 'm');结果
'This is my code'
^
'my code'您的第二个示例与以下内容完全相同:
$text = 'This is a test to test code';
echo strrchr($text, 't');结果
'This is a test to test code'
^
't code'我所做的这个功能实现了你的期望:
/**
* Give the last occurrence of a string and everything that follows it
* in another string
* @param String $needle String to find
* @param String $haystack Subject
* @return String String|empty string
*/
function strrchrExtend($needle, $haystack)
{
if (preg_match('/(('.$needle.')(?:.(?!\2))*)$/', $haystack, $matches))
return $matches[0];
return '';
}它使用的正则表达式可以在这里进行测试:演示
示例
echo strrchrExtend('test', 'This is a test to test code');输出
test code发布于 2014-09-28 21:50:56
很简单!因为它会在字符串中找到字符的最后一次出现。一个字也没说。
它只是找到最后一个出现的字符,然后它将从该位置echo字符串的其余部分。
第一个示例中的:
$text = 'This is my code';
echo strrchr($text, 'my');它找到最后一个m,然后打印包含的重置m本身:my code
第二个示例中的:
$text = 'This is a test to test code';
echo strrchr($text, 'test');它找到最后一个t,并像最后一个示例一样打印其余的:test code
更多信息
发布于 2014-09-28 21:50:42
来自PHP文档:
干草堆要搜索的字符串
针如果针包含多个字符,则只使用第一个。这种行为不同于strstr()。
在您的示例中,只使用针(t)的第一个字符。
https://stackoverflow.com/questions/26089966
复制相似问题