note 95198 modified in function.str-replace by thiago

From: Date: Tue, 01 Jun 2010 04:14:39 +0000
Subject: note 95198 modified in function.str-replace by thiago
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-169762@lists.php.net to get a copy of this message
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

« previous php.notes (#169762) next »