Home > Net >  Using preg_match in DOMXpath for mathing text contgent
Using preg_match in DOMXpath for mathing text contgent

Time:04-15

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 :

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

CodePudding user response:

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

  • Related