DiigIT | IT Community
No Profile Image
Welcome Guest
New User? Register | Login

Regexp Help

By: rekha singh | 17 Jun 2010 12:31 pm

How do code with php regexp(preg match & replace) to be able to receive inputs from both formats date : ie 12 -14 April 2009, 12Mac - 14April 2009 then output it to format From : yyyy-mm-dd To yyyy-mm-dd ie From :2009-04-12 To: 2009-04-14.

 

Comments

So, i'm having a little trouble wrapping my head around this at the moment.

 
I have a number of very large XML files, and I'm trying to mold it into a structure that I can use (not being xml). Here is a sample:
 
<card name="Abomination" graphics="Abominati on.jpg" text="Whenever Abomination blocks or becomes blocked by a green or white creature, destroy that creature at end of combat.">
<attr key="rarity" value="U1" />
<attr key="cost" value="{3}{B} {B}" />
<attr key="color" value="Black" />
<attr key="type" value="Creature" />
<attr key="subtype" value="Horror" />
<attr key="power" value="2" />
<attr key="toughness" value="6" />
</card>
 
I was trying to write some regex that would stick all the attributes of <card> into an array so i could just add them as attributes like the others (into key->value pairs). So ideally it would look like this:
 
<card>
<attr key="name" value="Abomination" />
<attr key="graphics" value="Abomination. jpg" />
<attr key="text" value="Whenever Abomination blocks..." />
 
Does anyone have any ideas? I will probably parse the XML with php's built in parser when I have all the attributes the same. Any help is much appreciated!
 
Thanks,
 
By: rekha singh | 17 Jun 2010

 Ah! Cataloging your Magic: The Gathering Cards.

 
You might try using the preg_match function with the following pattern:
 
/^(?: <attr key=")(?<key> .+)(?: " value=")(?<value> .+)(?: "/>)$/
 
So for each line in your file, you would run it through a preg_match that looks like this:
 
preg_match(' /^(?: <attr key=")(?<key> .+)(?: " value=")(?<value> .+)(?: "/>)$/', $line, $matches);
 
Line, of course, is your line of data. I would trim() the line before I ran it through the regex function.
 
This should place the string between the quotes after the string attr key= into $matches['key' ] and the string between the quotes after value= into $matches['value' ]. The rest of the line is in non-capturing parentheses, so it should not capture. Other tags, such as your <card> </card> tags should not match at all.
 
It has been awhile since I have written a complex regex, so I can't be sure I escaped everything that needs to be escaped.
 
You might create a loop that will read each line of your xml files individually, looking for your sets of data, capturing for each line and then writing to your database, or whatever you are doing with this data.
 
Let me know if this works for you.
 
By: rekha singh | 17 Jun 2010

Leave a comment

Enter the text in the image
img
Can't read?
Type the characters you see in the picture below.


Close Move