简体   繁体   English

在页面中检测CSS类并在PHP中编写if / else

[英]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. 我有一个页面需要检测CSS类,然后使用PHP应用if / else语句。 How do I do that? 我怎么做?

HTML 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". 检测并找到“ insights”类并显示“是的,它存在”的PHP代码是什么。 If there's no class of that name then show "No, it doesn't exists." 如果没有该名称的类别,则显示“否,它不存在”。

How should I achieve this? 我应该如何实现呢?

There is a library that named Simple HTML DOM Parser. 有一个名为简单HTML DOM解析器的库。 You can parse the dom with it and access elements that you wanted. 您可以使用它解析dom并访问所需的元素。 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');

A simple solution would be to just use strpos 一个简单的解决方案是只使用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 可以像这样在php中使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM