Thomas
Thomas

Reputation: 573

Selecting background url from style attribute with XPATH (and PHP)

I'd like to select only the url from this background image style attribute, is that possible with XPATH?

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

i have something like

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

Upvotes: 3

Views: 2419

Answers (2)

Danish Akhtar
Danish Akhtar

Reputation: 1

$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>';

Upvotes: 0

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243459

Use:

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

XSLT-based verification:

<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>

when this transformation is applied on the provided XML document:

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

the wanted, correct result is produced:

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

Upvotes: 1

Related Questions