dozabg1616 2013-07-16 12:24
浏览 48
已采纳

从关联数组中的值替换字符串

I'm given a string of HTML with some "tokens" in it. They are structured like {:TOKEN_NAME:}

For instance:

<!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>

I am also given an associative array, with the token names, and what they should be replaced with, as such:

    // Populate and pull all global smarttags
    private function PullGlobalSmartTags($values){
        return array(array('Name'=>'{:TITLE:}', 'Replacement'=>'<title>' . $values[0] . '</title>'),
                     array('Name'=>'{:DESCRIPTION:}', 'Replacement'=>'<meta name="description" content="' . $values[1] . '" />'),
                     array('Name'=>'{:KEYWORDS:}', 'Replacement'=>($values[22]) ? null : '<meta name="keywords" content="' . $values[2] . '" />'),
                     array('Name'=>'{:GOOGLE-UA:}', 'Replacement'=>'<script type="text/javascript">var _gaq = _gaq || [];_gaq.push([\'_setAccount\', \'' . $values[3] . '\']);_gaq.push([\'_trackPageview\']);(function(){var ga = document.createElement(\'script\');ga.type = \'text/javascript\'; ga.async = true;ga.src = (\'https:\' == document.location.protocol ? \'https://ssl\' : \'http://www\') + \'.google-analytics.com/ga.js\';var s = document.getElementsByTagName(\'script\')[0]; s.parentNode.insertBefore(ga, s);})();</script>'),
                     array('Name'=>'{:GOOGLE-VERIFY:}', 'Replacement'=>'<meta name="google-site-verification" content="' . $values[4] . '" />'),
                     array('Name'=>'{:BING-VERIFY:}', 'Replacement'=>'<meta name="msvalidate.01" content="' . $values[5] . '" />'),
                     array('Name'=>'{:PAGE-CONTENT:}', 'Replacement'=>$values[6]),);
    }           

Please assume all values in $values populate, and populate correctly (because they do...)

I know with str_replace, and preg_replace I can simply pass arrays in as my needle, replacement, and haystack, however everything I am seeing only shows non-associative arrays.

My question is, how can I do these replacements? I know that I could simply loop through the array, and do my replacements one at a time, but is there a way to do this without looping?

This does do the trick:

        for($i=0; $i<$gsCt; ++$i){
            $rettemp = str_replace($GlobalSmartTags[$i]['Name'], $GlobalSmartTags[$i]['Replacement'], $rettemp);
        }

however, I do not believe it is the most efficient method to do this.

  • 写回答

1条回答 默认 最新

  • doutang2017 2013-07-16 12:31
    关注

    Try this

    $replace = PullGlobalSmartTags($values);
    str_replace(array_column($replace, 'Name'), array_column($replace,'Replacement'), $html);
    

    This only works with PHP 5 >= 5.5.0. Reference: array_column

    Here is couple of suggestion till you upgrade to 5.5.0.

    You can convert your replace array to single dimension array like this and replace.

    $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);
    

    Or you can change the function PullGlobalSmartTags to return single dimension array and use str_replace as above. You can even use the method you suggested, but it has much more replace in a loop.

    I won't suggest compiling from code on production server unless there is an absolute necessity.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler