1

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 swap 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."

1 Answer 1

1
    foreach($dataArray as $key=>$value)
    {
     $text= str_replace("@".$key,$value,$text);
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! Would you consider preg_replace instead of str_replace in this situation? Maybe some performance improvements, or what do you think?
I don't really think that preg_replace will be more efficient... in fact php.net says that : "If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of ereg_replace() or preg_replace()."
@MikalBen do you need these improvements? Or you're asking "just in case?" If so - forget PHP at all, write in machine codes directly into RAM. It would be significantly faster. If you don't have idea what it is - don't ask such questions anymore.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.