t = c("I","like","hot","dogs","a","lot","hot","dogs","forever")
replace_phrases <- function(vec, ph){
while(1){
ind = c()
l = 0
for(j in 1:length(ph)){
ind1 = match(ph[[j]], vec)
if(all(!is.na(ind1))){
if(length(ind) == 0 || ind[1] > ind1[1]){
ind = ind1
l = ph[[j]]
}
}
}
if(length(ind) == 0){
return(vec)
break
}else{
vec[ind[1]] = paste(l, collapse = '_')
vec = vec[-ind[2:length(ind)]]
}
}
}
replace_phrases(t, list(c("hot", "dogs")))
replace_phrases(c("ab","pq","xy"), list(c("ab","pq"),c("pq","xy")))