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?

2
  • It sounds like you're looking for something called a "DOM parser". Commented Apr 14, 2017 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: stackoverflow.com/questions/819182/… - then apply RegEx to check. Commented Apr 14, 2017 at 11:40

2 Answers 2

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');
Sign up to request clarification or add additional context in comments.

Comments

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);

2 Comments

Thank you. How do I write this in PHP with the else statement? I'm pretty new to this.
if ($contains) { echo "yes, it exists"; } else { echo "no, it don't exist"; }

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.