-2

I'm importing a XML tag into WordPress

<inspection>21-Oct-2018 10:30AM to 10:50AM</inspection>

I need to seperate the date and time into two seperate fields with PHP

So

Field 1 = 21 Oct 2018
Field 2 = 10:30am to 10:50am

I know this is a very broad question but does anyone know how to achieve this in PHP?

Gonçalo Peres
  • 11,752
  • 3
  • 54
  • 83
Paul D
  • 17
  • 4
  • How are you receiving the XML? Just as a string, or in some XML DOM library? – Dai Oct 19 '18 at 00:35
  • Possible duplicate of [How do you parse and process HTML/XML in PHP?](https://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php) –  Oct 19 '18 at 00:44
  • Receiving the XML as a String @Dai – Paul D Oct 19 '18 at 00:46
  • What exactly is the issue? Start by parsing XML using an XML parser. That leaves you with a string which you could simply `explode` on its first space to mostly end up with the desired result. Where exactly are you stuck in this process? – deceze Oct 19 '18 at 00:57

1 Answers1

0

This isn't really an elegant solution but it works, if the inspection date never truly deviates from how it is displayed.

$str = "<inspection>21-Oct-2018 10:30AM to 10:50AM</inspection>";
preg_match('/(\d+\-[A-Za-z]+\-\d{4})\s(.+\s.+\M)/',$str,$temp);
echo $temp[1]."\n";
echo $temp[2]."\n";

Outputs

21-Oct-2018
10:30AM to 10:50AM

Use https://regex101.com/ for explanation of Regular Expression as I could not do it justice with my explanation.

Hope this helps.

as function:

function sep_times($str){
    preg_match('/(\d+\-[A-Za-z]+\-\d{4})\s(.+\s.+\M)/',$str,$temp);
    return $temp;
}

Use:

$variable = sep_times($your_xml_string); //"<inspection>21-Oct-2018 10:30AM to 10:50AM</inspection>"

echo $variable[0]; //outputs 21-Oct-2018 10:30AM to 10:50AM
echo $variable[1]; //outputs 21-Oct-2018
echo $variable[2]; //outputs 10:30AM to 10:50AM
hirnspiel
  • 1
  • 3