Replacing section of HTML file
Hi, I am trying to replace a section of an HTML document while keeping the rest of it intact.
Original (test.html)
<html>
<head>
<title>Test</title>
</head>
<body>
Text and code that stays
<!--a-->
Replace this and everything below
</body>
</html>
This is where I've got to:
#!/usr/bin/perl
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
print "Content-type: text/html\n\n";
$file = "test.html"; # Page to edit
# Open the file #######
open(TFL, "<$file") || die "Can't open $file\n";
@thefile=<TFL>;
close(TFL);
open(TFL, ">$file") || die "Can't open $file\n";
foreach $line (@thefile){
if($line =~ /<!--a-->/i) {
print TFL "<!--a-->\n";
print TFL "New Stuff\n</body>\n</html>\n";
}
}
close(TFL);
exit;
# end
When I use this, the entire file gets replaced.
How do I replace only the file contents after the "!--a--" tag?
Hope someone can help, many thanks - Ted
Good.Things posted this at 19:50 — 1st May 2007.
He has: 6 posts
Joined: Apr 2007
I don't know what language this is but I can almost assure you this is the line you want to modify :
if($line =~ //i)
It's controlling everything else more or less.
Good Things Services
Abhishek Reddy posted this at 04:19 — 2nd May 2007.
He has: 3,348 posts
Joined: Jul 2001
You probably want something like this:
sub replace_from_mark {
my ($mark, $newstuff, $text) = @_;
$text =~ s/$mark.*/$newstuff/gs;
return $text;
}
# ...
open(TFL, ">$file") || die "Can't open $file\n";
$text = replace_from_mark("<!--a-->\n",
"New Stuff\n</body>\n</html>\n",
join("", @thefile));
print TFL $text;
close(TFL);
Instead of walking every line, it uses a regular expression substitution.
Tedh posted this at 09:32 — 2nd May 2007.
They have: 21 posts
Joined: Nov 2004
Thanks Abhishek,
I'll check this out soon (in the middle of some work at moment) and let you know how it goes.
cheers - Ted
Tedh posted this at 11:45 — 2nd May 2007.
They have: 21 posts
Joined: Nov 2004
Abhishek, that works a treat. Many, many thanks.
I'm able to replace an entire lower part of html page no problem (which is one of my objectives).
I ended up putting the new stuff into a variable
#!perl
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
print "Content-type: text/html\n\n";
# Variables
$file = "test.html"; # Page to edit
$mark="<!--a-->";
$newstuff = "<!--a-->\nAll my new stuff";
# Open the file #######
open(TFL, "<$file") || die "Can't open $file\n";
@thefile=<TFL>;
close(TFL);
sub replace_from_mark {
my ($mark, $newstuff, $text) = @_;
$text =~ s/$mark.*/$newstuff/gs;
return $text;
}
# Replace it
open(TFL, ">$file") || die "Can't open $file\n";
$text = replace_from_mark("$mark\n", "$newstuff\n<\/body>\n<\/html>\n", join("", @thefile));
print TFL $text;
close(TFL);
print "The code has been replaced\n";
exit;
# end
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.