在PHP上的'空标记'中写入值

I have a written script that searches every id= in the .html file.

PHP:

<?php
$html = file_exists('test.html') ? file_get_contents('test.html') : die('unable to open the file');

$data['test'] = 'WRITE 1';

$data['test2'] = 'WRITE 2';

foreach ($data as $search => $value)
{
    $html = preg_match('%<[^>]*id="'.$search.'"[^>]*>([^<]*)</[^>]*>%', $html, $match) ? str_replace($match[1],$value,$html) : false;
}

echo $html;
?>

HTML:

<html>
<head>
<title>TRY</title>
</head>
<body>
<div id="test">A</div>
<div id="test2"></div>
<div id="test3">C</div>
</body>
</html>

the problem is it only writes on tags which is 'not empty' but on empty tag like id=test2 it escapes and will not write any values. Is there anyone can help me how to write on 'empty tags'?

the output above is:

WRITE 1
C

which it will escapes the empty tags like id="test2"

but my desired output is:

WRITE 1
WRITE 2
C

Update your replace part to:

$html = preg_match('%<[^>]*(id="'.$search.'"[^>]*>)([^<]*)</[^>]*>%', $html, $match) ? str_replace($match[1] . $match[2], $match[1] . $value,$html) : false;

This will replace also part of tag starting from ID to itself. So, you never will have an empty string.