/** * Replaces all occurrences of $searchOrMapping by $replace. * * This method provides 3 signatures: * * replace(string, string): * * $result = $myString->replace('search', 'replace'); * * Replaces all occurrences of "search" by "replace". * * replace(array(string), string): * * $needles = array( * 'first', * 'seconds' * ); * $result = $myString->replace($needles, 'replace'); * * Replaces all string that are contained in the $needles array by "replace". * * replace(array(string=>string)): * * $mapping = array( * 'first' => 'last', * 'hello' => 'world' * ); * $result = $myString->replace($mapping); * * Expects an associative array that represents a mapping of strings * as argument. * The keys are replaced by the assigned values. * In this example occurrences of "first" are replaced by "last" and * "hello" is replaced by "world". * * @param string|Mol_DataType_String|array(integer|string=>string|Mol_DataType_String) $searchOrMapping * @param string|Mol_DataType_String $replace * @return Mol_DataType_String The string with applied replacements. */ public function replace($searchOrMapping, $replace = null) { $search = $this->toValues($searchOrMapping); if ($replace === null && is_array($searchOrMapping)) { // Mapping provided. $replace = $search; $search = array_keys($searchOrMapping); } return $this->createString(Mol_Util_String::replace($this->value, $search, $replace)); }
/** * Tests signature replace(string, array(string=>string)): * Checks if replace() applies the mapping of search/replace pairs to the string. */ public function testReplaceAppliesMappingIfAssociativeArrayIsProvided() { $mapping = array('hello' => 'welcome', 'world' => 'home'); $result = Mol_Util_String::replace('hello world', $mapping); $this->assertEquals('welcome home', $result); }