note 95686 added to function.str-replace
| From: | MatthewPurdon at osu1 dot php dot net | Date: | Fri, 15 Jan 2010 22:14:46 +0000 |
| Subject: | note 95686 added to function.str-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-165013@lists.php.net to get a copy of this message | ||
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;
});
----
Server IP: 72.55.140.6
Probable Submitter: 173.32.220.24
----
Manual Page -- http://www.php.net/manual/en/function.str-replace.php
Edit -- https://master.php.net/note/edit/95686
Del: integrated -- https://master.php.net/note/delete/95686/integrated
Del: useless -- https://master.php.net/note/delete/95686/useless
Del: bad code -- https://master.php.net/note/delete/95686/bad+code
Del: spam -- https://master.php.net/note/delete/95686/spam
Del: non-english -- https://master.php.net/note/delete/95686/non-english
Del: in docs -- https://master.php.net/note/delete/95686/in+docs
Del: other reasons-- https://master.php.net/note/delete/95686
Reject -- https://master.php.net/note/reject/95686
Search -- https://master.php.net/manage/user-notes.php