Hướng dẫn
Quảng cáo

Hàm strrchr() trong PHP

Hướng dẫn cách sử dụng hàm strrchr() trong lập trình PHP

Tác dụng của hàm strrchr()

The strrchr() function find the last occurrence of a character within a string, and returns all the characters from that character to the end of the string (including that character).

The following table summarizes the technical details of this function.

Return Value: Returns the portion of the string from the last occurrence of a specified character to the end of the string, or FALSE if character is not found.
Changelog: Since PHP 8.0, passing an int as char is no longer supported.
Version: PHP 4+

Syntax

The basic syntax of the strrchr() function is given with:

strrchr(string, char);

The following example shows the strrchr() function in action.

<?php
// Sample string
$str = "Mary had a little lamb";

// Searching string
echo strrchr($str, "l");
?>

Warning: Prior to PHP 8.0, if char is not a string, it is converted to an integer and applied as the ASCII value of that number. This behavior has been deprecated since PHP 7.3.0, and no longer supported since PHP 8.0. Therefore, don't rely on it.


Parameters

The strrchr() function accepts the following parameters.

Parameter Description
string Required. Specifies the string to search in.
char Required. Specifies the character to find within the string. If more than one character is specified, only the first character will be considered.

More Examples

Here're some more examples showing how strrchr() function actually works:

The following example shows how to get the filename from a URL using this function.

<?php
// Sample URL
$url = "http://example.com/posts/index.php";

// Extracting filename from URL
echo strrchr($url, "/")."<br>";
echo substr(strrchr($url, "/"), 1);
?>

The following example demonstrates how to get the file extension from a filename.

<?php
// Sample path
$path = "/assets/theme-1.5.min.css";

// Extracting file extension
echo strrchr($path, ".")."<br>";
echo substr(strrchr($path, "."), 1);
?>

Bài viết này đã giúp ích cho bạn?

Bài viết mới

Advertisements