开发者

String-manipulation in PHP, insert array keys in user defined string

开发者 https://www.devze.com 2023-01-31 00:42 出处:网络
I have a function that takes the input of a user defined string and an array of data (key=>value), which looks like this;

I have a function that takes the input of a user defined string and an array of data (key=>value), which looks like this;

$text = "Hi! My name is @name, and I live in @location.";
$dataArray = array("name" => "Mikal", "location" => "Oslo, Norway");

function MakeString($text, array $dataArray)
{
// return manipulated string...
}

I would like my function to s开发者_运维技巧wap the string @variables with data from the array, where string-variable matches array-key (if it does), so that the function returns:

"Hi! My name is Mikal, and I live in Oslo, Norway."


    foreach($dataArray as $key=>$value)
    {
     $text= str_replace("@".$key,$value,$text);
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消