Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using preg_match in DOMXpath for mathing text contgent

I’m looking for a correct syntax for matching specific pattern #some_string# in text content in DOMDocument.

$document = <<<XML
<div>
    <para>text not to match</para>
    <para>Other line #my_pattern_to_match#, hello world</para>
    <block>
        <para>Second test #other_pattern_to_match# in a sub child node</para>
    </block> 
</div>
XML;

$xpath = new DOMXPath($document);

$xpath->registerNamespace("php", "http://php.net/xpath");
$xpath->registerPHPFunctions('preg_match');

$nodes = $xpath->query('//*[text()][0 < php:functionString("preg_match", "/\#(.*?)#/")]');

i’ve as result :
preg_match() expects at least 2 parameters, 1 given

With :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$nodes = $xpath->query('//para/text()[0 < php:functionString("preg_match", "/\#(.*?)#/")]');

an empty DOMNodeList()

I’m sure it’s the query syntax the problem. But i don’t know how to write the correct syntax.

>Solution :

I don’t know how to implement the preg_match into an xpath query but you could alternatively just pull all para elements and run the regex on them.

$document = <<<XML
<div>
    <para>text not to match</para>
    <para>Other line #my_pattern_to_match#, hello world</para>
    <block>
        <para>Second test #other_pattern_to_match# in a sub child node</para>
    </block> 
</div>
XML;
$dom = new DOMDocument;
$dom->loadXML($document);
$paras = $dom->getElementsByTagName('para');
foreach($paras as $para){
    if(preg_match('/#(.*?)#/', $para->nodeValue, $match)){
        echo $match[1] . PHP_EOL;
    }
}

https://3v4l.org/imChg

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading