22

Possible Duplicate:
XPath: How to match attributes that contain a certain string

I'm trying to parse some html with PHP DOM Xpath, but I'm having problems searching for a class name when the element has more than one. I found that if I use the hole attribute value like

$xpath->query('//div[@class="precodet precodeturgente"]'); 

it works, but if I do

$xpath->query('//div[@class="precodet"]');

it won't give me the node value. Sometimes there's only one class, others there are more than one, so what I want to know is if there's a way to search for a single class name.

Community
  • 1
  • 1
yoda
  • 10,834
  • 19
  • 64
  • 92

1 Answers1

44

You should be able to do

$xpath->query('//div[contains(@class,"precodet")]');
eagle12
  • 1,658
  • 11
  • 14
  • 11
    this would match any class that begins with precodet, for example `XprecodetY` would be matched – Maxim Krizhanovsky Jul 31 '13 at 13:29
  • 7
    What would be solution for matching exactly this class, but not any other class that begins with "precodet" ? – KoviNET Aug 27 '16 at 08:56
  • @KoviNET btw w3s needs to be taken carefuly, but there's quite nice description of the basic syntax - https://www.w3schools.com/xml/xpath_syntax.asp, functions - https://www.w3schools.com/xml/xsl_functions.asp and operators - https://www.w3schools.com/xml/xpath_operators.asp ..... I gave it more thoughts and testing and came up with a solution - let's consider class `boo`: `"//div[@class='boo' or starts-with(@class, 'boo ') or ' boo'=substring(@class, string-length(@class)- string-length(' boo') +1) or contains(@class, ' boo ')]"` - now PHP DOMXPath doesn't support `ends-with` => substring – jave.web Feb 16 '23 at 19:04
  • @KoviNET ... as mentioned here https://stackoverflow.com/a/5435487/1835470 it's an issue of `DOMXPath` only ["Supports XPath 1.0"](https://www.php.net/manual/en/class.domxpath.php); btw be aware `//div[@class='precodet']` matches ONLY when there is just that 1 class and no spaces around it - `div class="precodet"`; on the other hand the solution above supports all 4 cases - class at start, class at end, just class with no spaces and class somewhere in between other classes - note where there are spaces ` ` around `boo` => ***that is crucial*** for it to work properly – jave.web Feb 16 '23 at 19:10
  • Also note that you can combine this with nesting, so you can actually do `//div[selectormagic]//div[selectormagic]` so effectively you can achieve `.a .b` (note the double `//` between divs), for `.a > .b` you'd use just single `/` between divs – jave.web Feb 16 '23 at 19:56