Getting 2 values from 2 lines

Discussion in 'PHP' started by Joeker, Aug 20, 2008.

  1. #1
    I have a page's content which is formatted as follows:

    I want to get the name and the job in its own variables.

    Here is my code so far, which does not work 100%:

    
    <?php
        $matches1 = array();    
        $pos = strpos($content,"\n");
        $name = substr($content, 0, $pos);
        preg_match('$Name: ([a-z ]+)$i', $name, $matches1);
        $name = $matches1[1];
        
        $matches2 = array();  
        $second = substr($content, $pos);
        $pos2 = strpos($second,"\n");
        $job = substr($second, 0, $pos2);
        preg_match('$Job: ([a-z ]+)$i', $job, $matches2);
        $job = $matches2[1];
    ?>
    
    PHP:
    Anyone help?
     
    Joeker, Aug 20, 2008 IP
  2. William[ws]

    William[ws] Peon

    Messages:
    47
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    
    <?php
    $content = "
    Name: Joe Blow
    Job: Construction Worker"; \\ or however u wanna get the content.
    
    preg_match('/^Name: (.*)$/im', $name, $matches);
    
    print_r($matches); \\ Just output for u to know which array value its in
    
    preg_match('/^Job: (.*)$/im', $name, $matches2);
    
    print_r($matches2); \\ Again output so u can refrence.
    ?>
    
    Code (markup):
     
    William[ws], Aug 20, 2008 IP
  3. jack_ss

    jack_ss Guest

    Messages:
    94
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #3
    This should work:
    preg_match('/Name: (.*)\n/i', $content, $m);
    $name = $m[1];
    preg_match('/Job: (.*)\n/i', $content, $m);
    $job = $m[1];
    PHP:
     
    jack_ss, Aug 20, 2008 IP
  4. AimHigher

    AimHigher Member

    Messages:
    40
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #4
    Here's a nicer way to do it:

    
    <?php
    
    $matches = array();
    preg_match_all("/Name: ([A-Z \']+)\r\nJob: ([A-Z ]+)/i", $content, $matches);
    print_r($matches);
    
    ?>
    
    PHP:
     
    AimHigher, Aug 20, 2008 IP