Skip to content Skip to sidebar Skip to footer

Get Tags That Start With Uppercase In Xpath (php)

I'm trying to get html tags that start with uppercase using DOMDocument in PHP 5.3. I'm using a php function registered in XPath to test it, but the function is receiving as first

Solution 1:

Load the code as XML and not HTML. The HTML is not case-sensitive.

$xmlDoc->loadXML('<html>');

instead of:

$xmlDoc->loadHTML('<html>');

Solution 2:

A complete working example (test.php):

$doc = new DOMDocument;
$doc->load('test.xml');

$xpath = new DOMXPath($doc);
$xpath->registerNamespace("php", "http://php.net/xpath");
$xpath->registerPHPFunctions("isUpper");

functionisUpper($name) {
    return (bool)preg_match('/^[A-Z]/', $name);
}

$els = $xpath->query('//*[php:function("isUpper", name())]');

foreach ($elsas$el) {
    echo$el->nodeValue . "\n";
}

test.xml:

<test><A>Match this</A><b>Dont match this</b></test>

Output:

lwburk$ php test.php 
Match this

Solution 3:

Use this one-liner:

//*[contains('ABCDEFGHIJKLMNOPQRSTUVWXYZ', substring(name(),1,1))]

this selects any element in the XML document, the first character of whose name is contained in the string of all capital letters.

XSLT - based verification:

<xsl:stylesheetversion="1.0"xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:outputomit-xml-declaration="yes"indent="yes"/><xsl:templatematch="/"><xsl:copy-ofselect=
  "//*[contains('ABCDEFGHIJKLMNOPQRSTUVWXYZ', substring(name(),1,1))]"/></xsl:template></xsl:stylesheet>

when this transformation is applied on the provided XML document:

<test><A>Match this</A><b>Dont match this</b></test>

the XPath expression is evaluated and the selected nodes (in this case just one) are copied to the output:

<A>Match this</A>

Post a Comment for "Get Tags That Start With Uppercase In Xpath (php)"