note 95198 modified in function.str-replace by thiago

[email protected]
Newsgroups php.notes
Message-ID <[email protected]>
Feel free to optimize this using the while/for or anything else, but this is a bit of code that allows you to replace strings found in an associative array.

For example:
<?php
$replace = array(
'dog' => 'cat',
'apple' => 'orange'
'chevy' => 'ford'
);

$string = 'I like to eat an apple with my dog in my chevy';

echo str_replace_assoc($replace,$string);

// Echo: I like to eat an orange with my cat in my ford
?>

Here is the function:

<?php
function strReplaceAssoc(array $replace, $subject) {
   return str_replace(array_keys($replace), array_values($replace), $subject);    
}
?>

[Jun 1st, 2010 - EDIT BY thiago AT php DOT net: Function has been replaced with an updated version sent by ljelinek AT gmail DOT com]

--was--
Feel free to optimize this using the while/for or anything else, but this is a bit of code that allows you to replace strings found in an associative array.

For example:
<?php
$replace = array(
'dog' => 'cat',
'apple' => 'orange'
'chevy' => 'ford'
);

$string = 'I like to eat an apple with my dog in my chevy';

echo str_replace_assoc($replace,$string);

// Echo: I like to eat an orange with my cat in my ford
?>

Here is the function:

<?php
function str_replace_assoc($array,$string){
	$from_array = array();
	$to_array = array();
	
	foreach ($array as $k => $v){
		$from_array[] = $k;
		$to_array[] = $v;
	}
	
	return str_replace($from_array,$to_array,$string);
}
?>

http://php.net/manual/en/function.str-replace.php
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.