Home > Backend Development > PHP Tutorial > How Can I Replace Only the First (or Last) Occurrence of a Substring in PHP?

How Can I Replace Only the First (or Last) Occurrence of a Substring in PHP?

Mary-Kate Olsen
Release: 2024-12-17 12:17:24
Original
259 people have browsed it

How Can I Replace Only the First (or Last) Occurrence of a Substring in PHP?

Replacing Only the First Occurrence with str_replace

While there's no built-in str_replace function that limits its replacement to the first occurrence, a relatively straightforward solution exists without resorting to intricate hacks.

To achieve this, utilize the strpos function to locate the position of the substring within the main string. Once identified, employ substr_replace to modify the original string, specifying the occurrence position and the length of the substring. This method efficiently replaces the first occurrence without the overhead of regular expressions.

Code Example:

$haystack = "This is a sample string";
$needle = "is";
$replace = "was";

$pos = strpos($haystack, $needle);
if ($pos !== false) {
    $newstring = substr_replace($haystack, $replace, $pos, strlen($needle));
}

echo $newstring; // Output: "This was a sample string"
Copy after login

Bonus: To replace the last occurrence, substitute strpos with strrpos:

$pos = strrpos($haystack, $needle);
if ($pos !== false) {
    $newstring = substr_replace($haystack, $replace, $pos, strlen($needle));
}
Copy after login

The above is the detailed content of How Can I Replace Only the First (or Last) Occurrence of a Substring 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