1

I am writing an HTML file using file_put_content(), but want to be able to add additional content later by pulling the current file contents and chopping off the known ending to the html.

So something along these lines:

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

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

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

But since I can't just subtract strings, how can I remove the known string from the end of the file contents?

slimeArmy
  • 113
  • 6
  • 1
    if you KNOW how long the unwanted stuff is, then just use `substr()` to rip it out. – Marc B Jul 26 '16 at 20:18
  • If you need to append to an HTML document, even if it's just right at the very end, it's probably better to use a dom parser than string manipulation. – Don't Panic Jul 26 '16 at 20:27

1 Answers1

0

substr can be used to cut off a know length from the end of a string. But maybe you should determine if your string really ends with your suffix. To reach this, you can also use substr:

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

If the case not play any role, you can omit strtolower.

On the other side you can use str_replace to inject your content:

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

Maybe, Manipulate HTML from php could be also helpful.

Community
  • 1
  • 1
u-nik
  • 488
  • 4
  • 12