note 95686 deleted from function.str-replace by danbrown
| From: | danbrown@php.net | Date: | Fri, 15 Jan 2010 22:16:55 +0000 |
| Subject: | note 95686 deleted from function.str-replace by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-165014@lists.php.net to get a copy of this message | ||
Note Submitter: Matthew Purdon
----
I find it's much cleaner to perform the desired result that Wes is accomplishing by using
simple array manipulation functions. Note that this is a PHP5.3+ example as I am using a lambda.
<?php
namespace Util;
/**
* Utility Class for working with text
*/
class Text
{
/**
* Replace occurences of $replacements keys in $text with values from
* the provided $replacements array
*
* @param array $replacements
* @param string $text
* @return string
*/
public function replace($replacements, $text)
{
$searchFor = array_keys($replacements);
$replaceWith = array_values($replacements);
// If the values are an array convert them to CSV
$replaceWith = array_map(function($value) {
if (is_array($value)) {
return implode(',', $value);
}
return (string) $value;
}, $replaceWith);
return str_replace($searchFor, $replaceWith, $text);
}
}
?>
I wish the parameters of array_map where $array, $callback. It would look a lot prettier like this I
think:
<?php
$replaceWith = array_map($replaceWith, function($value) {
if (is_array($value)) {
return implode(',', $value);
}
return (string) $value;
});