<?php
/**
* Resolves dependencies for HTML documents.
*
* This script aims to resolve external dependencies (CSS, JS) linked in an HTML file.
* It provides a minimal solution with no external dependencies beyond core PHP.
*
* @param string $html_content The HTML content as a string.
* @return string The HTML content with dependencies resolved (CSS and JS links updated).
*/
function resolveDependencies(string $html_content): string
{
// Regex to find <link> and <script> tags.
$css_regex = '/<link[^>]*rel="stylesheet"[^>]*href="([^"]*)"[^>]*>/i';
$js_regex = '/<script[^>]*src="([^"]*)"[^>]*>/i';
// Resolve CSS dependencies.
$html_content = preg_replace_callback($css_regex, function ($matches) use ($html_content) {
$href = $matches[1];
// Resolve relative URLs.
if (strpos($href, '/') === 0) {
//Absolute URL, no changes needed.
return $matches[0];
} elseif (strpos($href, '.') === 0) {
//Relative to current directory
$href = realpath($href);
if($href === false){
return $matches[0]; //Keep original if realpath fails
}
$href = str_replace($_SERVER['DOCUMENT_ROOT'], '', $href); //remove document root
if(strpos($href, '/') === 0){
$href = $_SERVER['DOCUMENT_ROOT'] . $href;
}
} else {
// Relative to parent directory
$path = pathinfo($href, PATHINFO_DIRNAME);
$href = $path . '/' . $href;
}
//Check if the resolved path is valid
if (strpos($href, '.') === 0) {
return $matches[0]; //keep original if invalid path
}
return str_replace($href, $_SERVER['DOCUMENT_ROOT'] . $href, $matches[0]); // Replace with absolute path.
}, $html_content);
// Resolve JavaScript dependencies.
$html_content = preg_replace_callback($js_regex, function ($matches) use ($html_content) {
$src = $matches[1];
// Resolve relative URLs.
if (strpos($src, '/') === 0) {
//Absolute URL, no changes needed.
return $matches[0];
} elseif (strpos($src, '.') === 0) {
//Relative to current directory
$src = realpath($src);
if($src === false){
return $matches[0]; //Keep original if realpath fails
}
$src = str_replace($_SERVER['DOCUMENT_ROOT'], '', $src); //remove document root
if(strpos($src, '/') === 0){
$src = $_SERVER['DOCUMENT_ROOT'] . $src;
}
} else {
// Relative to parent directory
$path = pathinfo($src, PATHINFO_DIRNAME);
$src = $path . '/' . $src;
}
//Check if the resolved path is valid
if (strpos($src, '.') === 0) {
return $matches[0]; //keep original if invalid path
}
return str_replace($src, $_SERVER['DOCUMENT_ROOT'] . $src, $matches[0]); // Replace with absolute path.
}, $html_content);
return $html_content;
}
//Example Usage (replace with your HTML content)
$html = '<html>
<head>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href../styles/main.css">
</head>
<body>
<script src="script.js"></script>
<script src="js/utils.js"></script>
</body>
</html>';
$resolved_html = resolveDependencies($html);
echo $resolved_html;
?>
Add your comment