2017-03-15 30 views
0

我正在使用str_replace()函數替換文本文件中的某些內容。我的代碼:
PHP - 與str_replace關聯的函數僅在需要時運行

$txt = file_get_contents('script.txt'); 
function makefile() { 
    $file = fopen("test.txt","w"); 
    fwrite($file,"Hello World. Testing!"); 
    fclose($file); 
    return "Done!"; 
} 
$templates = array("{{time}}", "{{PI}}", "{{make}}"); 
$applied = array(date("h:i:sa"), 22/7, makefile()); 
$str = str_replace($templates, $applied , $txt); 
echo $str; 


的script.txt包含:

The time is {{time}} <br> 
The value of PI is {{PI}} 


正如你所看到的,它只是一個簡單的模板系統。 makefile()函數僅用於測試目的。 script.txt文件沒有{{make}}模板。所以通常情況下,替換操作期間不需要調用makefile函數。但是當我運行代碼時,它會創建test.txt。這意味着makefile()運行。有什麼辦法可以避免這種不必要的功能操作?只有在需要時才運行它們?

+0

由於makefile是創建文件的目的,它將在函數運行後立即創建文件。這是沒有辦法的。即使你循環遍歷並且分別替換,只是在進行替換時調用makefile,在寫入文件之前它不會返回'Done!',所以'{{make}}'不會被替換。如果不調用最後創建文件的函數,這可能是最接近的。 PHP沒有任何setTimeout類來延遲創建文件的代碼的執行,以便異步繼續makefile並在完成後寫入。 –

+0

您只需將邏輯移動到下面的文件中,而不是使用str_replace替換「{{make}}」。從str_replace中的數組中刪除'{{make}}'和相應的'makefile',然後在下面檢查if(strpos($ txt,'{{make}}')!== false){makefile(); }'所以如果字符串中存在'{{make}}',那麼你最後調用makefile。 –

回答

1

您需要添加strpos檢查。 strpos在php中用於查找子字符串在字符串中的位置,但如果子字符串從不出現,那麼它將返回false。利用這一點,我們可以這樣做:

<?php 

$txt = "The time is {{time}} <br> 
The value of PI is {{PI}}"; 
function makefile() { 
    $file = fopen("test.txt","w"); 
    fwrite($file,"Hello World. Testing!"); 
    fclose($file); 
    return "Done!"; 
} 
$templates = array("{{time}}", "{{PI}}", "{{make}}"); 
$applied = array(date("h:i:sa"), 22/7, strpos($txt,"{{make}}") ? makefile() : false); 
$str = str_replace($templates, $applied , $txt); 
echo $str; 

?> 
+0

謝謝。雖然這是一種間接的方式,但我希望這會有所幫助。 –

+0

更新的代碼:添加了內聯if語句,這應該使其更加簡潔。 – Neil

+0

更好! –