PHP 用数组中的值替换字符串 [英] PHP replace string with values from array
本文介绍了PHP 用数组中的值替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串,例如:
I have a string such as:
Hello <%First Name%> <%Last Name%> welcome
我有一个数组
[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
所以我的输出是
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']);
抱歉,我应该提到数组键和 <%First Name%>
Sorry I should of mentioned that the array keys may vary as well as the <%First Name%>
所以它甚至可以是 <%city%>
而数组可以是 city=>New York
so it could even be <%city%>
and the array can be city=>New York
推荐答案
你可以试试这个吗,
$string ="Hello <%First Name%> <%Last Name%> welcome";
preg_match_all('~<%(.*?)%>~s',$string,$datas);
$Array = array('0' => array ('First Name' => 'John', 'Last Name' => 'Smith' ));
$Html =$string;
foreach($datas[1] as $value){
$Html =str_replace($value, $Array[0][$value], $Html);
}
echo str_replace(array("<%","%>"),'',$Html);
这篇关于PHP 用数组中的值替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文