Skip to content

Instantly share code, notes, and snippets.

@zbee
Last active March 1, 2016 15:26
Show Gist options
  • Save zbee/feae70c0465e1e98cc29 to your computer and use it in GitHub Desktop.
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
//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
}
}
<?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