PHP variables with erroneous values after String manipulation

4

I have the following code:

$respostaXML = "<data-hora>2015-11-10T11:33:41.086-02:00</data-hora>";
$posTag = strpos($respostaXML,"<data-hora>");
$comprimento = (strpos($respostaXML,"</data-hora>") - strpos($respostaXML,"<data-hora>"));
$respDataHora = substr($respostaXML,$posTag,$comprimento);
$respData = substr($respDataHora,9,2) . "/" . substr($respDataHora,6,2) . "/" . substr($respDataHora,1,4);
$respHora = substr($respDataHora,12,8);

My intention is that in respData I get "10/11/2015" and in the "11:33:33" resp. It turns out the result is this:

respDataHora = 2015-11-10T11:33:41.086-02:00
respData = a>/ho/data                           
respHora = 015-11-1

The response time is OK, the response has already given this bizarre result (excerpts from the NAME of the previous variable), and the response must have given those numbers for the same reason.

The same code, with syntax differences and functions, of course, works perfectly in classic ASP. What's happening there?

    
asked by anonymous 11.11.2015 / 11:46

2 answers

0

Your problem was the tag <data-hora> you considered it at the time of doing strpos() and ended up getting the first position of it that was 0 , then I ended up doing this mess, I made an example removing these tags with str_replace() .

Example:

$xml = "<data-hora>2015-11-10T11:33:41.086-02:00</data-hora>";
$xml = str_replace("<data-hora>", "", $xml);
$respDataHora = str_replace("</data-hora>", "", $xml);
$respData = substr($respDataHora, 0, 10);
$respHora = substr($respDataHora, 11,8);
echo $respDataHora . '<br>';
echo $respData . '<br>';
echo $respHora . '<br>';

See working at Ideone .

    
11.11.2015 / 12:11
1

I think it would be easier to do for preg_match , since you have a well-defined%%.

$respostaXML = "<data-hora>2015-11-10T11:33:41.086-02:00</data-hora>";

$regex = '~<(data-hora)>(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})[\d\-\.:]*</>~';

preg_match($regex, $respostaXML, $match);

$data = $match[2];
$data = explode('-', $data);
$data = "{$data[2]}/{$data[1]}/{$data[0]}";

$hora = $match[3];

See Regex101

    
11.11.2015 / 11:57