在文件中添加一行

So I have this auto-generated HTML file. http://pastebin.com/mTMJNrdm

I'm trying to write a PHP script that replaces line 5 with this.

<LINK href="style.css" rel="stylesheet" type="text/css"></style>

I'm trying to wrap my head around it since it's a file. What function could accomplish this for me?

Current code:

$fh = file('standings.html');

$css = addslashes('<LINK href="style.css" rel="stylesheet" type="text/css"></style>');

$pattern = "</style>";

foreach ($fh as $lines) {
     if (preg_match($pattern, $lines)) {
         // Replace this line with $css
     }
}

php file function already reads an entire file into an array. Just replace the needed line by specifying the needed index:

$lines = file('standings.html');

$lines[4] = addslashes('<LINK href="style.css" rel="stylesheet" type="text/css"></style>');
$new_content = implode(" ", $lines);

file_put_contents('standings.html', $new_content);

check this code, i comment fopen and fwrite, check file permisions and uncomment.

<?php
$dom = new DOMDocument;

$dom->loadHTMLFile('file.html');


$elements = $dom->getElementsByTagName('style');

for ($i = $elements->length; --$i >= 0; ) {
    $s = $elements->item($i);


    $element = $dom->createElement('style', '');
    $domAttribute = $dom->createAttribute('href');
    $domAttribute->value = 'style.css';
    $element->appendChild($domAttribute);

    $domAttribute = $dom->createAttribute('rel');
    $domAttribute->value = 'stylesheet';
    $element->appendChild($domAttribute);

    $domAttribute = $dom->createAttribute('type');
    $domAttribute->value = 'text/css';
    $element->appendChild($domAttribute);

    $s->parentNode->replaceChild($element, $s);

}
$html = $dom->saveHTML();

/*
$file = fopen("file.html", "w+");
fwrite($file, $html);
*/

print_r("<pre>");
print_r($html);
print_r("</pre>");
die;