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

How Can I Replace Only the First Occurrence of a Substring in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-13 12:42:14704browse

How Can I Replace Only the First Occurrence of a Substring in PHP?

Replacing Only the First Occurrence with str_replace

There's no built-in variant of str_replace() that exclusively modifies a single occurrence. However, an elegant solution exists without resorting to convoluted approaches.

To limit replacement to the first match, employ the following procedure:

  1. Utilize strpos() to locate the position of the initial $search occurrence within the $subject string.
  2. If the position is not false, it means the occurrence was found.
  3. Create a new string $newstring using substr_replace(). This function performs the replacement at the specified position for the duration of the $needle's length.
$pos = strpos($haystack, $needle);
if ($pos !== false) {
    $newstring = substr_replace($haystack, $replace, $pos, strlen($needle));
}

This method is highly efficient, sidestepping the potential performance hit associated with regular expressions.

Bonus:

For replacing the last occurrence, simply replace strpos() with strrpos() in the above code.

The above is the detailed content of How Can I Replace Only the First Occurrence of a Substring in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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