0

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?

Elaine Byene
  • 3,868
  • 12
  • 50
  • 96
  • It sounds like you're looking for something called a "DOM parser". – David Apr 14 '17 at 11:32
  • As a general concept, PHP is working on the server side while HTML renders on the client side. Hence, unless you are loading someone else's page,you should be able to know what you are going to render. If you are rendering another's person code: do not. But if you still do: get content: http://stackoverflow.com/questions/819182/how-do-i-get-the-html-code-of-a-web-page-in-php - then apply RegEx to check. – nitobuendia Apr 14 '17 at 11:40

2 Answers2

2

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');
aprogrammer
  • 1,764
  • 1
  • 10
  • 20
1

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);
Philipp
  • 15,377
  • 4
  • 35
  • 52