Home > Net >  Replace items in a string with values from an array
Replace items in a string with values from an array

Time:11-01

I have a string of values separated by semicolon.

$str = 'value 12; another value; yet one more one; val5';

I also have an array where the keys correspond to the values in the string above.

How do I replace the values in the string with the values from the array? Now, I think I can explode the string by semi-colon and trim the space

$arr = array_map('trim', explode(';', $str));

Do I need to run the array through a loop and use the values as keys and then implode it back? Is there a faster way?

CodePudding user response:

str_replace() will accept arrays of tokens and values to replace them. Thus

<?php

$str = 'value 12; another value; yet one more one; val5';
$src = ["value 12", "another value", "yet one more one", "val5"];
$tgt = ["red","green","blue","violet"];

$res = str_replace($src, $tgt, $str);
echo $res;    // red; green; blue; violet

See: https://3v4l.org/kN8VW

CodePudding user response:

I think using str_ireplace can help you the most and code should look like below.

$str = 'value 12; another value; yet one more one; val5';
$assocArray = [
                  "value 12" => "Value goes here",
                  "another value" => "values_goes", 
                  "yet one more one" => "more value", 
                  "val5" => "value 5"
              ];
// if you need strict comparison with keys then go with str_replace
$newString = str_ireplace(array_keys($assocArray), $assocArray, $str);
  •  Tags:  
  • php
  • Related