PHP strrchr() Function: Description, Parameters, Return Value, and Usage Examples

This article explains the PHP strrchr() function, detailing its purpose of locating the last occurrence of a character in a string, describing its parameters and return value, and providing three practical code examples that demonstrate common usage scenarios.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP strrchr() Function: Description, Parameters, Return Value, and Usage Examples

Function Overview The string strrchr ( string $haystack , mixed $needle ) function searches for the last occurrence of a specified character (or the first character of a string) within the $haystack string and returns the portion of the string from that point to the end.

Explanation The function returns a substring of $haystack starting at the last occurrence of $needle. If $needle is not found, the function returns FALSE. When $needle contains more than one character, only its first character is considered, differing from strstr(). If $needle is not a string, it is converted to an integer and treated as an ASCII value.

Parameters

haystack : The string to be searched.

needle : The character or string to locate. If it is a string longer than one character, only the first character is used; non‑string values are cast to integers.

Return Value A substring of $haystack beginning with the last occurrence of $needle. If $needle is not found, FALSE is returned.

Example 1

<?php
$PATH = 'NAME:PASSWD:CHECK';
$dir = substr(strrchr($PATH, ':'), 1);
echo $dir; // 输出 CHECK

// 获取最后一行内容
$text = "Line 1
Line 2
Line 3";
$last = substr(strrchr($text, 10), 1);
echo $last; // 输出 line 3
?>

Example 2

<?php
echo strrchr("I love Shanghai!", "Shanghai"); // 输出 Shanghai!
?>

Example 3

<?php
echo strrchr("Hello world! What a beautiful day!", What); // 输出 What a beautiful day!
?>
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendprogrammingTutorialstring-functions
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.