Php 如何替换两个变量?
在我的页面顶部有一个面包屑Php 如何替换两个变量?,php,mysql,variables,ob-start,Php,Mysql,Variables,Ob Start,在我的页面顶部有一个面包屑 ob_start(); <li>##product##</li> <li>##category##</li> 然后我跑: <?php echo str_replace("##product##", $product, ob_get_clean()) ?> <?php echo str_replace("##category##", $category, ob_get_clean()) ?>
ob_start();
<li>##product##</li>
<li>##category##</li>
然后我跑:
<?php echo str_replace("##product##", $product, ob_get_clean()) ?>
<?php echo str_replace("##category##", $category, ob_get_clean()) ?>
变量$product被替换,我看到第二个变量不会被替换,因为我已经为product调用了ob_get_clean
如何使用ob_get_clean函数替换这两个字符串?试试以下方法:
$find = array("##product##", "##category##");
$replace = array($product, $category);
echo str_replace($find, $product, ob_get_clean());
将ob_get_clean的结果分配给变量:
$ob = ob_get_clean();
$ob = str_replace("##product##", $product, $ob);
$ob = str_replace("##category##", $category, $ob);
echo $ob;
问题是,您正在从一个来源回复这些变量 你能做的最好的事情是:
$from = array("##product##", "##category##");
$to = array($product, $category);
echo str_replace($from, $to, ob_get_contents());
或者,您可以在一行中运行多个函数。注意$replaced与输入和输出相同:
$replaced = ob_get_contents();
$replaced = str_replace("##product##", $product, $replaced);
$replaced = str_replace("##category##", $category, $replaced);
echo $replaced;
我认为,使用第一种方法是有效的,因为使用数据提供只调用它一次。使用:
<?php echo str_replace("##product##", $product, ob_get_contents()) ?>
<?php echo str_replace("##category##", $category, ob_get_contents()) ?>
如果使用,则在第一次调用后删除输出缓冲区。使用ob\u get\u内容,而不是ob\u get\u clean
$product = 'product 1';
$category = 'category1';
ob_start();
echo '<li>##product##</li>
<li>##category##</li>';
$template = ob_get_contents();
$template = str_replace("##product##", $product, $template);
$template = str_replace("##category##", $category, $template);
ob_end_clean();
echo $template;
ob_get_clean实际上执行ob_get_内容和ob_end_clean
str_replace[产品,类别],$product,$category,ob_get_clean];你为什么这么做?在页面顶部运行查询,首先正确生成面包屑。您可以在ob_start$callback中定义回调函数
$product = 'product 1';
$category = 'category1';
ob_start();
echo '<li>##product##</li>
<li>##category##</li>';
$template = ob_get_contents();
$template = str_replace("##product##", $product, $template);
$template = str_replace("##category##", $category, $template);
ob_end_clean();
echo $template;
<?php
ob_start();
echo str_replace("##product##", $product, ob_get_contents());
echo str_replace("##category##", $category, ob_get_contents());
?>