1

I'm looking for a clean way to grab and remove all the css between the <style></style> tags. For example:

<style>
foo
</style>

content

<style>
bar
</style>

here

By the end of the process I should have a string with content\nhere (everything not between the style tags) and an array of matches between the style tags ['foo', 'bar'] or something similar. I've tried a lot of different regex approaches and none of the seemed to work for me. (I'm no regex pro though..)

2 Answers 2

6

You should not access html with regular expressions. Just try DomDocument instead. It 's more cleaner and easier to access.

$dom = new DomDocument();
$dom->loadHTML('Your HTML here');

$elements = $dom->getElementsByTagName('style');
for ($i = $elements->length; --$i >= 0;) {
    $elements->item($i)->parentNode->removeChild($elements->item($i));
}

echo $dom->saveHTML();

This code is an example and not tested.

Sign up to request clarification or add additional context in comments.

10 Comments

Using the DOM is the good way for this kind of task, but don't imagine that using regex is 'too expensive', because using the DOM is slower (in particular, you must pay the cost of the DOM tree building). But as I said before it stays the most clean way.
@Marcel Nice approach here. Is it really faster then regex?
Don't forget to store or display $dom->saveHTML()
You could use foreach on the $elements.
@MK: no it's not possible, because $elements is not an array but a nodeList, and elements must be removed from the end to the begining.
|
1

I found the answer:

$html = "<style>css css css</style>my html<style>more css</style>";
preg_match_all("/<style>(.*?)<\/style>/is", $html, $matches);

$html = str_replace($matches[0], '', $html);
$css = implode("\n", $matches[1]);

echo $html; // my html
echi $css; // css css css \n more css

Originally I was looking for a pure regex solution, but this is fine for me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.