/** * Replaces occurrences of substring. * * This method tries to imitate behaviour of str_replace(). Though the * latter is already safe for utf-8, managed strings may use different * encodings as well. * As another convenience option $pattern may contain hash while * $replacement is null so mapping in hash is used * * @param string|array $pattern single (or set of) substring(s) to replace * @param string|array $replacement single (or set of) substring(s) * replacing related substring(s) in $pattern * @return \de\toxa\txf\string string with replacements applied */ public function replace($pattern, $replacement = null) { // using str_replace requires to use all strings encoded in UTF-8 if (is_array($pattern) && (is_array($replacement) || is_null($replacement))) { // normalize either array if (is_null($replacement)) { $usingHash = set::isHash($pattern); $replacement = static::wrapArray($usingHash ? array_values($pattern) : array()); $pattern = static::wrapArray($usingHash ? array_keys($pattern) : $pattern); } else { $replacement = static::wrapArray($replacement); $pattern = static::wrapArray($pattern); } // convert elements in either array to UTF-8 encoding foreach ($pattern as $key => $value) { $pattern[$key] = $value->asUtf8; } foreach ($replacement as $key => $value) { $replacement[$key] = $value->asUtf8; } // ensure both arrays containing same number of elements if (count($replacement) > count($pattern)) { $replacement = array_slice($replacement, 0, count($pattern)); } else { $replacement = array_pad($replacement, count($pattern), ''); } } else { if (static::isString($pattern) && (static::isString($replacement) || is_null($replacement))) { $pattern = static::wrap($pattern)->asUtf8; $replacement = static::wrap($replacement)->asUtf8; } else { throw new \InvalidArgumentException('provide two strings or 2 arrays'); } } // convert subject of replacement to UTF-8 as well $subject = $this->asUtf8; // perform str_replace $result = str_replace($pattern, $replacement, $subject); // finally convert result back from UTF-8 encoding to current one return static::wrap($result, 'utf-8')->convertTo($this->encoding); }