Skip to content

Instantly share code, notes, and snippets.

@rhagni
Created August 30, 2016 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rhagni/783c0c9011190e2d5559f2a567bec2bf to your computer and use it in GitHub Desktop.
Save rhagni/783c0c9011190e2d5559f2a567bec2bf to your computer and use it in GitHub Desktop.
Some combinations of recommendations to str_replace catches from comments of official documentation
<?php
/**
* Fastest and multimes str_replace
*
* Faster than str_replace when subject is an array and replace many times
* is possible from subject
*
*<code>
* $example = "<ht<html>ml> Malicious code </<html>html> etc";
* echo ultimate_str_replace(["<html>", "</html>"], "", $example);
* // Outputs: " Malicious code etc"
*</code>
*
* @see http://php.net/manual/en/function.str-replace.php#100871
*
* @see http://php.net/manual/en/function.str-replace.php#118785
*
* @param string|string[] $search
*
* @param string|string[] $replace
*
* @param string|string[] $subject
*
* @return string|string[]
*/
function ultimate_str_replace($search, $replace, $subject) {
if (is_array($subject)) {
foreach ($subject as &$sub) {
$sub = ultimate_str_replace($search, $replace, $sub);
}
} else {
$exists = 0;
do {
$subject = str_replace($search, $replace, $subject, $exists);
} while($exists);
}
return $subject;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment