理解strrchr函数

7

我正在使用函数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 code",而不是"test code"呢?谢谢。

3
根据PHP文档,“如果needle包含多个字符,则只使用第一个字符”。在第一个案例中,该字符是m,在第二个案例中是t - Mark Baker
2
@MarkBaker,那真的需要成为一个答案而不是一个评论,最好带上链接来源 :) - Moo-Juice
3个回答

2

为什么要使用 strrchr 函数呢?因为它可以在字符串中找到最后一次出现的一个字符,而不是单词。

它只会找到最后一次出现的字符,并从该位置开始输出剩余的字符串。


在您的第一个示例中:

$text = 'This is my code';
echo strrchr($text, 'my');

它找到最后一个m,然后打印包括m本身的重置:我的代码

在您的第二个示例中:

$text = 'This is a test to test code';
echo strrchr($text, 'test');

它会找到最后一个 t,并像最后一个示例一样打印剩余部分: test code

更多信息


2

来自 PHP 文档:

needle

如果 needle 包含多个字符,仅使用第一个字符。这种行为与 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

0

来自PHP文档:

haystack 要搜索的字符串

needle 如果needle包含多个字符,则仅使用第一个字符。这种行为与strstr()不同。

在您的示例中,只会使用needle的第一个字符(t)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接