2016-07-26 119 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可能也有帮助。