preg_match help

Discussion in 'PHP' started by promotingspace.net, Apr 14, 2010.

  1. #1
    Hi
    I have read some tutorials for preg_match but I cannot write patterns.
    Could someone help me?
    In the code below I need to read 80 in level="80"
    The bigger difficulty is that I have to make sure level="number" is within the <character > tag and make sure charUrl="r=Garona&amp;cn=Bob" exists in the same <character > tag
    
    $data='<character battleGroup="Rampage" charUrl="r=Garona&amp;cn=Bob" class="Hunter" 
    classId="3" level="80" name="Bob" >';
    PHP:
    Thanks for your help
     
    promotingspace.net, Apr 14, 2010 IP
  2. Kaimi

    Kaimi Peon

    Messages:
    60
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Try
    
    <?php
    $data='<character battleGroup="Rampage" charUrl="r=Garona&amp;cn=Bob" class="Hunter"
    classId="3" level="80" name="Bob" >';
    
    if(preg_match('/<character.{1,30} charUrl="r=Garona&amp;cn=Bob".{1,50}level="(\d+)"/s', $data, $match))
    {
    	print $match[1];
    }
    ?>
    
    PHP:
     
    Kaimi, Apr 14, 2010 IP
  3. promotingspace.net

    promotingspace.net Peon

    Messages:
    361
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    That worked thanks
    But I'll have to write similar code later. So please help me understand this code.
    I ask:
    1. You start the pattern with /<character => this means "<character" is required
    2. ".{1,30}" means combining with a string that can be 1-30 characters long
    3. ".{1,50}" the same as 2
    4. what is "(\d+)"?
    5. What is "/s"?
    Thanks in advance
     
    promotingspace.net, Apr 14, 2010 IP
  4. Kaimi

    Kaimi Peon

    Messages:
    60
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #4
    \d+ - 1+ digits
    /s - allows use of . to match a newline character
     
    Kaimi, Apr 14, 2010 IP