Elaine Byene
Elaine Byene

Reputation: 4142

Detect CSS class in a page and write if/else in PHP

I have a page where I need to detect a CSS class and then apply if/else statement using PHP. How do I do that?

HTML

<body>
    <div class="insights">
        Hello World
    </div>
</body>

What would be the PHP code to detect and find "insights" class exists and show "yes, it exists". If there's no class of that name then show "No, it doesn't exists."

How should I achieve this?

Upvotes: 0

Views: 5235

Answers (2)

aprogrammer
aprogrammer

Reputation: 1774

There is a library that named Simple HTML DOM Parser. You can parse the dom with it and access elements that you wanted. In your case you can do something like that :

include 'simple_html_dom.php';

$dom = str_get_html("<html><body><div class='insights'></div><div><div class='insights'></div></div></body></html>");

$elements = $dom->find('.insights');

echo count($elements) > 0 ? "It exists" : "No, it doesn't exists.";

If you want to fetch source from an url you can do it like that :

$dom = file_get_html('URL');

Upvotes: 2

Philipp
Philipp

Reputation: 15629

A simple solution would be to just use strpos

$contains = str($html, 'class="insights"') !== false;

a more complex and robust solution would be, to use a regular expression like the following

class="[^"]*\binsights\b[^"]*"

this could be used in php like this

$contains = (bool) preg_match('/class="[^"]*\binsights\b[^"]*"/', $html);

Upvotes: 1

Related Questions