Skip to content

Instantly share code, notes, and snippets.

@RobertAudi
Created July 23, 2010 16:26
Show Gist options
  • Save RobertAudi/487657 to your computer and use it in GitHub Desktop.
Save RobertAudi/487657 to your computer and use it in GitHub Desktop.
Replace first occurrence of the search string with the replacement string.
<?php
/**
* Replace first occurrence of the search string with the replacement string.
*
* @param string $needle : The value being searched for.
* @param string $replace : The replacement value that replaces found search values.
* @param string $haystack : The string being searched and replaced on.
* @return string : The (modified) haystack.
* @author tapken at engter dot de
* @link http://theserverpages.com/php/manual/en/function.str-replace.php#21735
*/
function str_replace_once( $needle, $replace, $haystack )
{
if ( ( $pos = strpos( $haystack, $needle ) ) === false )
return $haystack;
return substr_replace( $haystack, $replace, $pos, strlen( $needle ) );
} // End of str_replace_once
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment