Skip to content

Instantly share code, notes, and snippets.

@Medalink
Created February 2, 2012 17:10
Show Gist options
  • Save Medalink/1724616 to your computer and use it in GitHub Desktop.
Save Medalink/1724616 to your computer and use it in GitHub Desktop.
PHP Replace Text Once
<?php
function str_replace_once( $str_pattern, $str_replacement, $string ){
if( strpos( $string, $str_pattern ) !== false )
{
$occurrence = strpos( $string, $str_pattern );
return substr_replace( $string, $str_replacement, strpos( $string, $str_pattern ), strlen( $str_pattern ) );
}
return $string;
}
// How to use it:
$text = 'amazon amazon ebay ebay buy at amazon buy at amazon';
$replace_words = array( // text to search => text to replace
'amazon' => 'Amazon',
'ebay' => 'Ebay',
'buy at amazon' => 'buy at amazon'
);
foreach( $replace_words as $key => $value ) {
$text = str_replace_once( $key, $value, $text );
}
echo $text;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment