Created
February 2, 2012 17:10
-
-
Save Medalink/1724616 to your computer and use it in GitHub Desktop.
PHP Replace Text Once
This file contains 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 | |
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