Skip to content

Instantly share code, notes, and snippets.

@elusiveunit
Created November 20, 2013 20:17
Show Gist options
  • Save elusiveunit/7570255 to your computer and use it in GitHub Desktop.
Save elusiveunit/7570255 to your computer and use it in GitHub Desktop.
Two versions, equal in performance according to simple microtime testing. http://stackoverflow.com/questions/1252693/php-str-replace-that-only-acts-on-the-first-match
<?php
/**
* Replace the first occurrence in a string.
*
* @param string $search The value being searched for.
* @param string $replace The replacement value.
* @param string $subject The string being searched.
* @return string
*/
function str_replace_first( $search, $replace, $subject ) {
return implode( $replace, explode( $search, $subject, 2 ) );
}
<?php
/**
* Replace the first occurrence in a string.
*
* @param string $search The value being searched for.
* @param string $replace The replacement value.
* @param string $subject The string being searched.
* @return string
*/
function str_replace_first( $search, $replace, $subject ) {
$pos = strpos( $subject, $search );
if ( false !== $pos )
$subject = substr_replace( $subject, $replace, $pos, strlen( $search ) );
return $subject;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment