Last active
March 1, 2016 15:26
-
-
Save zbee/feae70c0465e1e98cc29 to your computer and use it in GitHub Desktop.
Replace one character in a string with a correlating item in an array of replacements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Before now or writing your own function you could only do String.prototype.replacewith a search and a replacement, | |
//or an array of searches to be repalced with their matching item in an array of replacements. | |
//Meaning you couldn't do something like replace all question marks in `cake ? pie ? noodles` with a matching | |
//item in an array of replacements, like this: `thatString.replace("?", ["meat","veggies"])` and get something like | |
//`cake meat pie veggies noodles`, but now you can! :D (note: number of occurences of search must match count() of $replace) | |
//"?no?".replaceArray("?", ["s","w"]) //returns `snow` | |
if (!String.prototype.replaceArray) { | |
String.prototype.replaceArray = function(find, replace) { | |
var x = 0 | |
var n = 0 | |
var str = "" | |
var string = this.split(find) | |
string.forEach(function(s) { | |
if (n > 0) { | |
str += replace[x] + s | |
x += 1 | |
} else { | |
str += s | |
} | |
n += 1 | |
}) | |
return str | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
#Before now or writing your own function you could only do str_replace() with a search and a replacement, | |
#or an array of searches to be repalced with their matching item in an array of replacements. | |
#Meaning you couldn't do something like replace all question marks in `cake ? pie ? noodles` with a matching | |
#item in an array of replacements, like this: `str_replace("?", ["meat","veggies"], $thatString)` and get something like | |
#`cake meat pie veggies noodles`, but now you can! :D (note: number of occurences of search must match count() of $replace) | |
#str_replace_arr("?", ["s","w"], "?no?") #returns `snow` | |
function str_replace_arr ($find, $replace, $string) { | |
$x = 0; | |
$n = 0; | |
$str = ''; | |
$string = explode($find, $string); | |
foreach ($string as $s) { | |
if ($n > 0) { | |
$str .= $replace[$x].$s; | |
$x += 1; | |
} else { | |
$str .= $s; | |
} | |
$n += 1; | |
} | |
return $str; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment