PHP variables with wrong values after string manipulation

Asked

Viewed 40 times

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 the answer I get "11/10/2015" and in the answer "11:33:33". It happens that the result is being this:

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

The respDataHora is OK, already the respData gave this bizarre result (excerpts from the NAME of the previous variable) and the respHora must have given these numbers for the same reason.

The same code, with different syntax and functions, of course, works perfectly in classic ASP. What’s going on there?

  • The problem was that I was pulling the String in respDataHora with tag and everything, because they are tags they do not appear in the page view. The correct code must have a "+11" at the end of the posTag and "-11" at the end of the variable length

2 answers

1

I think it would be easier to do preg_match, bearing in mind that you have a string 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\-\.:]*</\1>~';

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

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

$hora = $match[3];

See on Regex101

0


Your problem was the tag <data-hora> you considered her at the time to do the strpos() and ended up taking her first position 0, I ended up making this mess, I made an example by removing these tags with the 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 on Ideone.

  • you are capturing the timezone: substr($respDataHora, 24);

  • That’s Gabriel, that’s right. I discovered this by changing the "<" and ">" tags by Pipes. Thank you.

  • 1

    @Guilhermelautert had this detail, now it’s correct, thank you.

  • Why I won -1?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.