0

I need to find all the css references in a piece of code with regex

Suppose I have:

<link rel="stylesheet" type="text/css" href="mystyle.css">

The result of the match should be mystyle.css For now I only have ~href=\'.*\.css.*\'~ which matches the entire reference so it's not ok.

2
  • 1
    Better use DOM not regex Commented Jun 16, 2015 at 11:24
  • Why do you need to use a regex for this? Commented Jun 16, 2015 at 12:09

3 Answers 3

2

Karthik's answer is "almost" correct.

I made a "little" change in his example, which now also catches urls like:

http://blah.com/style.css

Modified regex is as follows:

~(?<=href=")[^"]+\.css~
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the following:

~(?<=href=")[^."]+\.css~

See DEMO

Comments

0

There is no good reason to use a regex for this. Read in the HTML file as a DOM document, and extract the stylesheet references with Xpath:

<?php

$doc = new DOMDocument();
$doc->loadHTMLFile("test.html");

$xpath = new DOMXpath($doc);

$stylesheets = $xpath->query("//link[@rel='stylesheet']/@href");

if ($stylesheets->length == 0) {
    echo "nothing found!\n";
} else {
    foreach ($stylesheets as $stylesheet) {
        echo "found stylesheet: " . $stylesheet->nodeValue . "\n";
    }
}

?>

That is, for each link element in the document (the //link part) where the rel property is stylesheet ([@rel='stylesheet']), extract the href attribute (/@href).

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.