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");
function isUpper($name) {
return (bool)preg_match('/^[A-Z]/', $name);
}
$els = $xpath->query('//*[php:function("isUpper", name())]');
foreach ($els as $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:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<xsl:copy-of select=
"//*[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)"