Simple HTML DOM wildcard in attribute

非 Y 不嫁゛ 提交于 2020-01-02 07:35:14

问题


I have the following tags

<div class="col *">Text</div>

* is anything.

I want to get all div tag with class attribute contains col (as in my example) using Simple HTML DOM.


回答1:


Since Simple HTML DOM does already have a method for selecting attributes that contain a certain value and|or something else. For example

$html->find("div[class*=col]", 0)->outertext

Or you could just retrieve div nodes that start with col like so

$html->find("div[class^=col]", 0)->outertext

And for safe keeping you can find all the other ways to filter attributes in this 3rd party plugin (By the way there are way better things for dealing with DOM that are based on libxml, a definitive list can be found here)

  1. [attribute] - Matches elements that have the specified attribute.
  2. [!attribute] - Matches elements that don't have the specified attribute.
  3. [attribute=value] - Matches elements that have the specified attribute with a certain value.
  4. [attribute!=value] - Matches elements that don't have the specified attribute with a certain value.
  5. [attribute^=value] - Matches elements that have the specified attribute and it starts with a certain value.
  6. [attribute$=value] - Matches elements that have the specified attribute and it ends with a certain value.
  7. [attribute*=value] - Matches elements that have the specified attribute and it contains a certain value.

Source: http://simplehtmldom.sourceforge.net/manual.htm




回答2:


I don't have a way how to test it at the moment, but as I looked into it (http://simplehtmldom.sourceforge.net/) it should be fairly simple.

$html = file_get_html('http://somesite.net');
foreach($html->find('div') as $div){
  if stripos($div->class,"col"){
    // this $div has a "col" class..
  }
}

or even simpler:

$html = file_get_html('http://somesite.net');
foreach($html->find('div.col') as $div){
  // every $div has a "col" class..
}

Does it work?



来源:https://stackoverflow.com/questions/13525124/simple-html-dom-wildcard-in-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!