问题
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)
[attribute]
- Matches elements that have the specified attribute.[!attribute]
- Matches elements that don't have the specified attribute.[attribute=value]
- Matches elements that have the specified attribute with a certain value.[attribute!=value]
- Matches elements that don't have the specified attribute with a certain value.[attribute^=value]
- Matches elements that have the specified attribute and it starts with a certain value.[attribute$=value]
- Matches elements that have the specified attribute and it ends with a certain value.[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