[英]str_replace in a file doesn't work
我正在嘗試使用preg_replace刪除html文件中的html和body標簽,但不是替換所需的標簽,而是整個html文件變為空白。 我不明白我要去哪里錯了...我覺得我在一個基本概念上錯了,但是不明白我在哪里使用這是代碼:
$f = fopen ("game1/game.html", "w");
$replacetags=array('<html>', '</html>', '<body>', '</body>','<head>','</head>')
$file= str_replace( $replacetags,'',$f);
fclose($f);
另外,如果有人可以建議刪除標簽的更好方法,那將是有幫助的。
您得到的輸出正確無誤。 當您替換這些標記'<html>', '</html>', '<body>', '</body>','<head>','</head>'
瀏覽器時,出現了問題無法將其呈現為普通網頁。 要在瀏覽器中顯示,您應該遵循正確的格式。
瀏覽器中應顯示以下格式
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
為您的信息
strip_tags —從字符串中剝離HTML和PHP標簽。 您可能也想看看。
str_replace不能與fopen處理程序一起使用(正如我在php ref上看到的那樣),因此您需要使用它
$replacetags=array('<html>', '</html>', '<body>', '</body>','<head>','</head>');
$file= str_replace( $replacetags,'',file_get_contents("game1/game.html"));
$f = fopen ("game1/game.html", "w");
fwrite($f,$file);
fclose($f);
fopen
函數打開文件句柄 (這是resource
類型)。
您可能要使用file_get_contents
和file_put_contents
函數。 他們實際上是將數據讀寫到文件中。
當您將重要標簽消除為body , head和html時 ,您將無法在瀏覽器中看到輸出。
因此, str_replace運行良好。您可以通過運行以下代碼對它進行交叉檢查:
<?php
$f =file_get_contents('game1/game.html');
$replacetags=array('<html>', '</html>', '<body>', '</body>','<head>','</head>') ;
$file= str_replace( $replacetags,"",$f);
file_put_contents("output.html", $file);
?>
在瀏覽器中運行或加載頁面(包含上述源代碼)后,使用文本編輯器打開生成的output.html
文件時,將看不到body,head和html標簽。
UPD: 為什么HTML文件完全空白 ?
在W模式下使用fopen打開文件或URL時,會發生以下情況:
'w': Open for writing only; place the file pointer at the
beginning of the file and truncate the file to zero length.
If the file does not exist, attempt to create it.
當您使用fopen將文件打開為fopen ("game1/game.html", "w");
,則文件指針位於文件的開頭,並且文件被截斷為零長度( 空白 ),因為您沒有在game.html中編寫任何內容,因此html文件變為空白。
還要注意 : str_replace中的第三個參數是the string or array being searched and replaced on, otherwise known as the haystack
。 但是在您的代碼中,您傳遞的第三個參數$ f是文件句柄。 結果,當您使用echo or print
輸出$file
字符串時,將打印資源ID #x而不是filter(targeted)字符串。
fopen應該是:
$file = fopen('game.html', 'w+');
您的game.html頁面已刪除您的代碼。 看看是否相信我
我也建議您使用str_ireplace
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.