PHP 用数组中的值替换字符串

编程入门 行业动态 更新时间:2024-10-28 06:30:42
本文介绍了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']);

抱歉,我应该提到数组键和

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

所以它甚至可以是 而数组可以是 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 用数组中的值替换字符串

本文发布于:2023-10-05 12:01:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1467362.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   组中   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!