skip to Main Content

I have this string

<itcc-ci:somevariabletext contextRef="cntxCorr_i" unitRef="eur" decimals="0">2020265</itcc-ci:somevariabletext>

I want remove all characters and print only 2020265.

How can I do that? I have used str_replace but it did not work. Any ideas?

I have use a htmlspecialchars() function, but now I have no idea. My string now is

&lt;itcc-ci:somevariabletext contextRef=&quot;cntxCorr_i&quot; unitRef=&quot;eur&quot; decimals=&quot;0&quot;&gt;2020265&lt;/itcc-ci:somevariabletext&gt;

3

Answers


  1. My suggestion is that we take advantage of the fact that this number is between the ‘>’ and ‘<‘ characters. If this is always the rule, then such code will help:

     $contextRef= '<itcc-ci:somevariabletext contextRef="cntxCorr_i" unitRef="eur" decimals="0">2020265</itcc-ci:somevariabletext>';
    
    $startPos = strpos($contextRef, '&gt;') + strlen('&gt;');
    $endPos = strpos($contextRef, '&lt;', $startPos);
    $length = $endPos - $startPos;
    $number = substr($contextRef, $startPos, $length);
    echo  $number;
    
    Login or Signup to reply.
  2. It is XML, so parse it as XML.

    $x = '<itcc-ci:somevariabletext contextRef="cntxCorr_i" unitRef="eur" decimals="0">2020265</itcc-ci:somevariabletext>';
    $d = new DomDocument();
    $d->loadXml($x);
    
    $list = $d->getElementsByTagName('itcc-ci:somevariabletext');
    foreach($list as $node) {
        var_dump($node->textContent);
    }
    

    This will produce a warning since it is not a full document and is missing the namespace declaration. You should parse the full document and use XML operations to extract the data that you want, rather than picking fragments out of the middle.

    See: https://www.php.net/manual/en/book.dom.php

    Login or Signup to reply.
  3. Your data is missing fundamental information. Assuming you have it all, and you just didn’t share it here:

    $input = '<?xml version="1.0" ?>
    <some-root-tag xmlns:itcc-ci="some-missing-uri">
        <itcc-ci:somevariabletext contextRef="cntxCorr_i" unitRef="eur" decimals="0">2020265</itcc-ci:somevariabletext>
    </some-root-tag>
    ';
    
    
    $xml = new SimpleXMLElement($input);
    $xml->registerXPathNamespace('itcc-ci', 'some-missing-uri');
    $value = (string)$xml->xpath('//itcc-ci:somevariabletext')[0];
    
    var_dump($value);
    

    Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search