Extracting Specific String Values

Discussion in 'PHP' started by kieranrobo, Jun 28, 2011.

  1. #1
    Hi,

    How would I extract specific data from a string? For example:
    
    <?
    $string= "Name: Bob<br>
    Age: 5 Years Old<br>
    Likes: None<br>";
    ?>
    
    PHP:
    That as an example, how would I get "5 Years Old" on its own when I specified "Age:" in the PHP code? For example, if I specified to the script to pick out "Age:", it would out put: "5 Years Old".

    Any help is GREATLY appreciated!
     
    kieranrobo, Jun 28, 2011 IP
  2. themullet

    themullet Member

    Messages:
    110
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    26
    #2
    could just use something like explode

    $a = explode("Name: ",$string);
    $b = explode("<br>",$a[0]);
    echo $b[0]; //this should return bob

    bit dirty however should work
     
    themullet, Jun 28, 2011 IP
  3. EricBruggema

    EricBruggema Well-Known Member

    Messages:
    1,740
    Likes Received:
    28
    Best Answers:
    13
    Trophy Points:
    175
    #3
    Yup or you can use regex using preg_match :)
     
    EricBruggema, Jul 2, 2011 IP
  4. BRUm

    BRUm Well-Known Member

    Messages:
    3,086
    Likes Received:
    61
    Best Answers:
    1
    Trophy Points:
    100
    #4
    Or you could use substr() to provide the range of characters to return. Quicker and more efficient than explode and regex.
     
    BRUm, Jul 7, 2011 IP