2012-12-06 36 views
0

朋友們您好,我無法使用PHP的str_replace();函數獲取所需結果。使用str_replace或preg_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

'ob_get_contents();'沒有分配給任何東西。 – nickb

+2

'$ content = ob_get_contents();' –

回答

2

您可以獲取緩衝區並用ob_get_clean()關閉它,然後進行替換並回顯$content,它會將其發送到瀏覽器。

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

感謝您的幫助。有效。 –