3

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');
4
  • And? Does it work? Is it giving you undesired results? Commented Sep 7, 2011 at 11:48
  • it will give the full content of the style attribute, I only want to select the content of the url('') Commented Sep 7, 2011 at 11:53
  • 1
    what's inside the style attribute is no longer part of the DOM, so it's not a job for XPath. You'd find a CSS parser to do that... I'm not aware of a solution for that as common as XPath or DOMDocument, maybe this speficic case is easiest done with a regex. Commented Sep 7, 2011 at 11:53
  • Good question, +1. See my answer for a complete, short and easy, oneliner XPath expression that produces exactly the wanted URL. Commented Sep 7, 2011 at 17:56

2 Answers 2

1

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"
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Code only answers aren't useful for the community. Please look at How to Answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.