How to Replace the Last Occurrence of a String in PHP?

Patricia Arquette
Release: 2024-11-06 01:03:02
Original
553 people have browsed it

How to Replace the Last Occurrence of a String in PHP?

Finding the Last String Occurrence with Precision

Replacing a specific occurrence of a string within a larger string can be a common programming task. However, finding the last occurrence can prove challenging without an efficient method.

Last Occurrence Replacement Solution

To address this, consider utilizing the str_lreplace() function, designed to replace the last occurrence of a specified string with a new string. Unlike other string replacement functions, this function pinpoints the last occurrence, even if it's not at the end of the string.

To illustrate its functionality:

<code class="php">function str_lreplace($search, $replace, $subject)
{
    $pos = strrpos($subject, $search);

    if($pos !== false)
    {
        $subject = substr_replace($subject, $replace, $pos, strlen($search));
    }

    return $subject;
}</code>
Copy after login

In this function, strrpos() locates the position of the last occurrence of the $search string in $subject. If found, substr_replace() modifies the subject string, replacing the $search occurrence with the $replace string.

Example Usage

Consider the following example:

<code class="php">$search = 'The';
$replace = 'A';
$subject = 'The Quick Brown Fox Jumps Over The Lazy Dog';</code>
Copy after login

Running str_lreplace($search, $replace, $subject) will produce:

The Quick Brown Fox Jumps Over A Lazy Dog
Copy after login

This demonstrates the function's ability to precisely replace the last occurrence of "The" in the subject string.

Implementing the str_lreplace() function in your codebase provides a straightforward and reliable method for performing last-occurrence string replacements, ensuring accuracy and efficiency in your string manipulation tasks.

The above is the detailed content of How to Replace the Last Occurrence of a String in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!