Hello. On the Internet there is a cloud of examples of how to replace the values ​​of one array with another. But nowhere (in a few hours) I didn’t find how to replace only those values ​​that meet certain criteria in the array.

Here the array_replace or str_replace can replace the values ​​of a single Array(0=>'odin',1=>'dva',2=>'tri'); Array(0=>'one',1=>'two',2=>'three');

But I just can not figure out how to replace only part of the line, so that something like this happens:

 // было так Array(0=>'odin',1=>'dva',2=>'tri'); // а хочу получить так Array(0=>'o(d)[i]n',1=>'(d)va',2=>'tr[i]'); 

Those. replace the letter i with [i] and replace the letter d with (d)

The only option I can implement is this (but I would like an option with regulars):

 foreach(Array(0=>'odin',1=>'dva',2=>'tri')as$y=>$z) { // дальше с каждым значением работать отдельно, // а после всё собирать в отдельный массив } 
  • one
    in any case, no matter how you look at each value, you will work separately, or the function you use will do it. What is the problem to write in your foreach line of the form data[$y] = str_replace("d", "[d]", $z) or an analogue with regular expressions, it is not clear. - teran

2 answers 2

Use the array_map function, Luke!

 $arr = ['odin', 'dva', 'tri']; // array_map проходится по массиву, заменяя значения на возвращённое значение $arr = array_map(function($el){ // Заменяем все d и i return preg_replace_callback("/d|i/", function($found){ return $found[0] === 'd' ? '(d)' : '[i]'; }, $el); }, $arr); var_dump($arr); 

https://repl.it/FEIG/0

  • Thanks, that is necessary! - dgd hsk
  • one
    @dgdhsk, You're welcome. - user207618

Use str_replace;

 $arr = Array(0=>"odin",1=>"dva",2=>"tri"); foreach ($arr as $r=>$z) { $arr[$r] = str_replace("i","[i]",$z); $arr[$r] = str_replace("d","(d)",$arr[$r]); } 
  • Thank you, but I already had this option. - dgd hsk
  • one
    Glad to try :) - L. Vadim