views:

348

answers:

2

I have a class that stores paths to CSS and Javascript files in arrays. This class also compiles my final page HTML output (which is stored in an $output variable). I want to loop through my $css and $js arrays and inject HTML at specific points in $output. The CSS files would need to go right before </head> and the JS files would need to go right before </body>

Having placeholder $cssFiles and $jsFiles variables within my HTML template files are not an option for me.

And just to complicate this further (sorry), I need a failsafe where if </head> and/or </body> do not exist within $output, the code would be injected at the very beginning of $output.

I assume this is a regex problem, but I don't know what the pattern(s) would be.

Thanks!

+1  A: 

Considering you are willing to "parse" HTML, which is not an easy task, I'm not sure regex are the right tool for the job, actually.

If your </head> and </body> where always there, I would suggest going with a simple str_replace : simpler, and faster than regex.

If those are not always there... It's going to be a lot harder, I suppose...

For the "end of the head" part, you could check if is here (with strpos, for instance) ; and, if not, try to insert you code after the </title> tag (simple : use str_replace), or the <meta> tags (inserting before the first " ; this will probably not be the end of the head section, but better than nothing.

For the "end of the body" part, you could check if the </body> is there ; andif not, just concatenate your code to the whole HTML string.


In any case, to "parse" HTML, I would not use regexes, but, instead, I'd go with some DOM manipulation tool, like the DOMDocument class that is bundled with PHP, and its DOMDocument::loadHTML method.

Pascal MARTIN
+4  A: 

I wouldn't use a regular expression when a simple str_replace() would suffice. It sounds like you've already identified clear places in the $output string to modify, so I'd do something like this:

$cssStr = '';
$jsStr = '';
foreach($css as $path) {
    $cssStr .= '<link rel="stylesheet" type="text/css" media="screen"'.
     'href="'.$path.'"/>';
}
if (strpos($output,'</head>') !== false)) {
    $output = str_replace('</head>',$cssStr.'</head>',$output);
} else {
    $output = $cssStr . $output;
}

foreach($js as $path) {
    $jsStr .= '<script type="text/javascript" src="'.$path.'"></script>';
}
if (strpos($output,'</body>') !== false)) {
    $output = str_replace('</body>',$jsStr.'</body>',$output);
} else {
    $output = $jsStr . $output;
}
zombat
Arms