2011-09-07 78 views
3

我想从此背景图像样式属性中只选择URL,XPATH可以吗?使用XPATH(和PHP)从样式属性中选择背景URL

<a href="http://www.test.com" style="background-image: url('http://www.test.com/hello.jpg');">test</a> 

我有类似

$url = $xpath->query('//a//@style'); 
+0

还有呢?它工作吗?它给你带来不希望的结果吗? –

+0

它会给出style属性的全部内容,我只想选择url('') – Thomas

+1

的内容。style属性中的内容不再是DOM的一部分,所以它不是XPath的工作。你会发现一个CSS解析器来做到这一点...我不知道像XPath或DOMDocument一样常见的解决方案,也许这个speficic案例最简单的用正则表达式来完成。 –

回答

1

使用

substring-before(substring-after(@style, "'"), 
       "'" 
       ) 

基于XSLT的验证

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output omit-xml-declaration="yes" indent="yes"/> 
<xsl:strip-space elements="*"/> 

<xsl:template match="/*"> 
    "<xsl:value-of select= 
    "substring-before(substring-after(@style, &quot;&apos;&quot;), 
         &quot;&apos;&quot; 
         ) 
    "/>" 
</xsl:template> 

</xsl:stylesheet> 

当这种转变是在所提供的XML文档应用:

<a href="http://www.test.com" style= 
"background-image: url('http://www.test.com/hello.jpg');">test</a> 

想要的,正确的结果产生

"http://www.test.com/hello.jpg" 
0

<?php 
 
$arrHolder = array(); 
 
     foreach ($xpath->query('//*[@style]') as $node) { 
 
      if (strpos($node->getAttribute('style'), 'background:url') !== FALSE) { 
 

 
       array_push($arrHolder, $node->tagName . " = " . $node->getAttribute('style')); 
 
      } 
 
     } 
 
     echo '<pre>'; 
 
     print_r($arrHolder); 
 
     echo '</pre>'; 
 
?>

+0

仅提供代码答案对社区无用。请看[如何回答](http://stackoverflow.com/questions/how-to-answer) – abpatil