0

I am trying to convert an XML document to JSON, but I have a situation where there are two different data types and one is removing the other to fix this. I tried a regular expression, in which I got most of the way there.

My question is, is there a better way to fix this than using a regex? And how can I fix this?

Original XML

<StartMonthGroup>
   <StartMonth withdrawn="false"><MajorOfferRound>12 Dec 2013</MajorOfferRound>Sep 2013
   </StartMonth>
   <StartMonth withdrawn="false">Jan 2014</StartMonth>
   <StartMonth withdrawn="false">May 2014</StartMonth>
</StartMonthGroup>

New XML

<StartMonthGroup>
  <MajorOfferRound>12 Dec 2013</MajorOfferRound>
  <StartMonth withdrawn="false">Sep 2013</StartMonth>
  <StartMonth withdrawn="false">Jan 2014</StartMonth>
  <StartMonth withdrawn="false">May 2014</StartMonth>
</StartMonthGroup>

PHP Code

public static function fixDates($data)
{
    if (preg_match("/<MajorOfferRound>/", $data)) {
        $data = preg_replace("/<StartMonth withdrawn=\"false\"><MajorOfferRound>/", "<MajorOfferRound>", $data);
        $data = preg_replace("/<\/MajorOfferRound>/", "</MajorOfferRound><StartMonth withdrawn=\"false\">", $data);

        $data = preg_replace("/<StartMonth withdrawn=\"true\"><MajorOfferRound>/", "<MajorOfferRound>", $data);
        $data = preg_replace("/<\/MajorOfferRound>/", "</MajorOfferRound><StartMonth withdrawn=\"true\">", $data);


        return $data;
    } else {
        return $data;
    }
}
Sebastian Zartner
  • 18,808
  • 10
  • 90
  • 132
Ardenexal
  • 543
  • 6
  • 20

1 Answers1

0

If you've decided regex is the best approach you could do all the replacing with in one shot.

$regex = '/(<S\w{9}\sw\w{8}=\"\w{4,5}\">)(\W{1,2}M\w{14}>)(.*)(<\/M\w{14}>)(.*)\W+(<\/S\w{9}>)/im'; 

$result = preg_replace($regex, "$2$3$4\n   $1$5$6", $data);

Here it is in action: http://ideone.com/RuoGtL

l'L'l
  • 44,951
  • 10
  • 95
  • 146