PHP replace string with values from array

2019-05-11 14:49发布

I have a string such as:

   Hello <%First Name%> <%Last Name%> welcome

and I have a array

 [0] => Array
    (
        [First Name] => John
        [Last Name] => Smith
    )

What I need to do is take the string and replace the words in <% with the actual text from the array

So my output would be

   Hello John Smith welcome

Im not sure how to accomplish this but I cant even seem to replace it with regular text

$test = str_replace("<%.*%>","test",$textData['text']);

Sorry I should of mentioned that the array keys may vary as well as the <%First Name%>

so it could even be <%city%> and the array can be city=>New York

7条回答
beautiful°
2楼-- · 2019-05-11 15:48

You can use this:

$result = preg_replace_callback('~<%(First|Last) Name)%>~', function ($m) {
    return $yourarray[$m[1] . ' Name']; } ,$str);

or much simple (and probably more efficient), use Brian H. answer (and replace search strings by <%First Name%> and <%Last Name%>).

查看更多
登录 后发表回答