What are some common techniques for replacing relative links with absolute links in HTML files using PHP?

When working with HTML files that contain relative links, it may be necessary to convert these links to absolute links for various reasons such as ensuring consistency or compatibility with certain systems. This can be achieved by using PHP to parse the HTML file, identify relative links, and replace them with absolute links based on the current domain or specified base URL.

<?php

$html = file_get_contents('example.html');
$base_url = 'https://www.example.com';

// Replace relative links with absolute links
$html = preg_replace('/(href|src)=\"(?!http)([^\"\>]+)\"/i', '$1="' . $base_url . '/$2"', $html);

file_put_contents('example_absolute.html', $html);

?>