Voting

: nine plus zero?
(Example: nine)

The Note You're Voting On

Wes Foster
15 years ago
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]

<< Back to user notes page

To Top