0

i need to replace string with array value and add some text after and before array value. i tried to find solution in google and stackoverflow.but i failed. Then I have a string, for example:

$string = "Hello...! :emo01:";

I have an array with Keys and Values, example:

$arr = array(":emo01:"=>"1f325", ":emo02:"=>"1f326", ":emo03:"=>"1f5b1");

and i need to code this function

function my_Function($arr,$string){

}

Would give the return as "Hello...! <img src='http://www.domain.com/1f325.png' />". how to write this 'my_Function' function.

1 Answers1

1

Solution work on general case.

$string = "Hello...! :emo01:";
$string2 = "Hello...! :emo01::emo02:";

$arr = array(":emo01:"=>"1f325", ":emo02:"=>"1f326", ":emo03:"=>"1f5b1");


function my_Function($arr, $string){

    $arrNewArray = [];

    foreach($arr as $key => $value ) {
        $arrNewArray[$key] = '<img src="http://yourdomain.com/'. $value .'.png" />';
    }

    return str_replace(array_keys($arrNewArray), $arrNewArray, $string);

}

echo my_Function($arr, $string);
echo my_Function($arr, $string2);
christian Nguyen
  • 1,530
  • 13
  • 11