2016-07-26 115 views
1

我正在使用file_put_content()寫入HTML文件,但希望能夠稍後通過拉取當前文件內容並切斷HTML的已知結尾來添加其他內容。從字符串末尾刪除已知字符

所以這些方針的東西:

$close = '</body></html>'; 

$htmlFile = file_get_contents('someUrl'); 
$tmp = $htmlFile - $close; 

file_put_contents('someUrl', $tmp.'New Content'.$close); 

但因爲我不能只減去字符串,我怎麼能刪除的文件內容的末尾已知的字符串?

+1

如果你知道多餘的東西是多久,那麼只需使用'substr()'來撕掉它。 –

+0

如果您需要附加到HTML文檔,即使它剛好在最後,最好使用dom解析器而不是字符串處理。 –

回答

0

substr可用於從字符串末尾切斷已知長度。但是,也許你應該確定你的字符串是否真的以你的後綴結尾。爲了達到這一點,你也可以使用substr

if (strtolower(substr($string, -strlen($suffix))) == strtolower($suffix)) { 
    $string = substr($string, 0, -strlen($suffix)); 
} 

如果情況沒有起到任何作用,則可以省略strtolower

在另一邊,你可以使用str_replace注入您的內容:

$string = str_replace('</body>', $newContent . '</body>', $string); 

也許,Manipulate HTML from php可能也有幫助。