使用str_replace或preg_replace更改图像路径

时间:2012-12-06 13:21:37

标签: php str-replace

朋友您好我无法使用PHP的str_replace ();函数获得所需的结果。

我的代码是这样的:

<?php ob_start (); /* Start Buffering */

$layout = 'climate';

?>

<div>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc pellentesque.</p>

<img src="images/industry/pic1.jpg"/>
<img src="products/images/industry/pic2.jpg"/>
<img src="samples/products/images/industry/pic3.jpg"/>

</div>

<?php ob_get_contents();  /* Get the Buffer */

$content = str_replace('/desktop/', $layout . '/images/', $layout);

echo $content;

ob_end_flush (); /* Send Output to the browser */

?>

现在我要做的就是让整个页面生成,然后我想获取生成的页面并替换它的路径中的特定单词。最后将缓冲区发送到浏览器。

请注意:

非常新的PHP 因此请您帮我纠正此代码以更正语法。

我的输出中的这些路径是由我使用的CMS生成的,因此我无法控制它们。

$layout变量的值由另一个PHP函数指定。我没有提到那个片段只是为了避免混淆。

由于我的主题是非JavaScript ,我不打算使用任何JavaScript。

期望的输出:

我希望/industry/在整个页面中被/$layout/的值替换,然后再将其发送到浏览器。

<div>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc pellentesque.</p>

<img src="images/climate/pic1.jpg"/>
<img src="products/images/climate/pic2.jpg"/>
<img src="samples/products/images/climate/pic3.jpg"/>

</div>

最后:

如果你觉得比这个更好,请随意提出任何其他解决方案。

1 个答案:

答案 0 :(得分:2)

您可以使用ob_get_clean()获取缓冲区并关闭它,然后进行替换并回显$content,然后将其发送到浏览器。

$content = ob_get_clean();  
$content = str_replace('/industry/', '/' . $layout . '/', $content);
echo $content;