Php 从Assoc数组中的值替换字符串
我得到了一个包含一些“标记”的HTML字符串。它们的结构类似于Php 从Assoc数组中的值替换字符串,php,preg-replace,associative-array,str-replace,preg-replace-callback,Php,Preg Replace,Associative Array,Str Replace,Preg Replace Callback,我得到了一个包含一些“标记”的HTML字符串。它们的结构类似于{:TOKEN\u NAME:} 例如: <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scal
{:TOKEN\u NAME:}
例如:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
{:TITLE:}
{:DESCRIPTION:}
{:KEYWORDS:}
{:GOOGLE-VERIFY:}
{:BING-VERIFY:}
<link rel="stylesheet" href="/assets/css/base.styles.css?_=<?php echo time(); ?>" type="text/css" />
<link rel="stylesheet" href="/assets/css/custom.css?_=<?php echo time(); ?>" type="text/css" />
<!--[if lt IE 9]>
<script type="text/javascript" src="/assets/js/modernizr.min.js"></script>
<![endif]-->
</head>
<body>
<article data-role="page-wrapper" class="container-fluid">
<header class="row-fluid" data-role="page-header">
<h1 class="span5 logo pull-right"><a href="http://www.o7thwebdesign.com">o7th Web Design</a></h1>
<nav class="span7">
{:PAGE-CONTENT:}
</nav>
</header>
<section class="row-fluid" data-role="page-container">
</section>
<footer class="row-fluid" data-role="page-footer">
</footer>
</article>
<script type="text/javascript" src="/assets/js/scripts.js?_=<?php echo time(); ?>"></script>
<script type="text/javascript" src="/assets/js/custom.js?_=<?php echo time(); ?>"></script>
{:GOOGLE-UA:}
</body>
</html>
但是,我不认为这是最有效的方法。试试这个
$replace = PullGlobalSmartTags($values);
str_replace(array_column($replace, 'Name'), array_column($replace,'Replacement'), $html);
这仅适用于PHP5>=5.5.0。参考:
在升级到5.5.0之前,这里有几个建议
您可以像这样将替换数组转换为一维数组并替换
$replace = PullGlobalSmartTags($value);
$kv = array();
for ($i=0;$i<count($replace);$i++){
$kv[$replace[$i]['Name']]=$replace[$i]['Replacement'];
}
$rettemp = str_replace(array_keys($kv),array_values($kv),$rettemp);
$replace=PullGlobalSmartTags($value);
$kv=数组();
对于($i=0;$iI不需要搜索任何内容,请重新阅读问题您使用的是哪个php版本?php 5.4(或任何最新版本),我的服务器最新的5.4.9是最稳定的版本,这是我运行的。我已经升级了我的服务器。它仍然显示5.4.9是最新的版本。我运行的是Ubuntu13.04服务器,不,我不会从源代码编译。我不想让你失望,我希望以后能够尝试,如果不是明天的话第一件事。谢谢你坚持这一点:)效果很好。我将不得不将这个q添加到书签中,因为当我的服务器可以获得PHP5.5时,似乎array_列将使它更加高效。谢谢你的帮助
$replace = PullGlobalSmartTags($values);
str_replace(array_column($replace, 'Name'), array_column($replace,'Replacement'), $html);
$replace = PullGlobalSmartTags($value);
$kv = array();
for ($i=0;$i<count($replace);$i++){
$kv[$replace[$i]['Name']]=$replace[$i]['Replacement'];
}
$rettemp = str_replace(array_keys($kv),array_values($kv),$rettemp);