DiDom\Query::cssToXpath PHP Method

cssToXpath() public static method

Converts a CSS selector into an XPath expression.
public static cssToXpath ( string $selector, string $prefix = '//' ) : string
$selector string A CSS selector
$prefix string Specifies the nesting of nodes
return string XPath expression
    public static function cssToXpath($selector, $prefix = '//')
    {
        $pos = strrpos($selector, '::');
        if ($pos !== false) {
            $property = substr($selector, $pos + 2);
            $property = self::parseProperty($property);
            $property = self::convertProperty($property['name'], $property['args']);
            $selector = substr($selector, 0, $pos);
        }
        if (substr($selector, 0, 1) === '>') {
            $prefix = '/';
            $selector = ltrim($selector, '> ');
        }
        $segments = self::getSegments($selector);
        $xpath = '';
        while (count($segments) > 0) {
            $xpath .= self::buildXpath($segments, $prefix);
            $selector = trim(substr($selector, strlen($segments['selector'])));
            $prefix = isset($segments['rel']) ? '/' : '//';
            if ($selector === '') {
                break;
            }
            $segments = self::getSegments($selector);
        }
        if (isset($property)) {
            $xpath = $xpath . '/' . $property;
        }
        return $xpath;
    }

Usage Example

示例#1
0
 /**
  * @dataProvider invalidSelectorProvider
  */
 public function testInvalidSelector($selector)
 {
     $this->setExpectedException('RuntimeException');
     Query::cssToXpath($selector);
 }