Created
November 20, 2013 20:17
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ) ); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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