-2

i have an array like this

$array = [
    'item1' => 'red', 
    'item2' => 'blue#foo#',
    'item3' => 'green',
    'item4' => 'white#foo2#',
    'item5' => 'bla#foo3#ck',
    'item6' => 'yellow#foo#'];

i wan't to get all word with surrounded by #word# like that (word can be anything)

$list = array_unique([ "#foo#", "#foo2#", "#foo3#", #foo#" ]);

and replace $list in $array with my data

$data = ['John', 'California', 'Cola', .......];

and go get finally

$array = [
    'item1' => 'red', 
    'item2' => 'blueJohn',
    'item3' => 'green',
    'item4' => 'whiteCalifornia',
    'item5' => 'blaColack',
    'item6' => 'yellowJohn'];

if someone can advice me.

Edit to @mickmackusa thanks for the link but, but how i can get my $list ? and it's not really effeciancy because if my initial array have a lot of rows the loop can take some times, but thanks.

Is it the only way to do this with a loop ?

thanks in advance.

ITS
  • 31
  • 9
  • 1
    That's not very clear what do you want to replace those words with. Post your desired result of this array – HTMHell Aug 24 '19 at 22:21
  • I edited my publication, hoping that the problem was well explained and I am always listening if someone has a better idea than a loop – ITS Aug 24 '19 at 23:12

1 Answers1

0

No, you don't have to use a loop to perform replacements, but php is going to "iterate" the array no matter what syntax you use.

Regex provides a more concise code, but if you want better performance, strtr() inside of a loop will very likely perform faster.

I will declare your input data as $array in my snippets. Both examples to follow will provide this output:

array (
  'item1' => 'red',
  'item2' => 'blueJohn',
  'item3' => 'green',
  'item4' => 'whiteCalifornia',
  'item5' => 'blaColack',
  'item6' => 'yellowJohn',
)

Looped strtr(): (Demo)

$translations = [
    '#foo#'  => 'John',
    '#foo2#' => 'California',
    '#foo3#' => 'Cola',
];

foreach ($array as &$item) {  // modify values by reference with & symbol
    $item = strtr($item, $translations);  // translate placeholder to desired substring from lookup array
}

var_export($array);

preg_replace(): (Demo) *notice pattern delimiters are added to the lookup array

$translations = [
    '~#foo#~'  => 'John',
    '~#foo2#~' => 'California',
    '~#foo3#~' => 'Cola',
];

var_export(preg_replace(array_keys($translations), $translations, $array));

p.s. If you don't know how to generate your $list, then I can't fathom how you will be able to know how to translate particular placeholders into the appropriate value. I am assuming you have enough project-logic knowledge to write an appropriate translation/lookup array.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • thanks, for $list i probablly use regex to find #words# and build translations, it's can be anything because the initial array depends on which part of the project call the method and i want to globalize for all. – ITS Aug 25 '19 at 12:59