SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Nov 2010
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Regular expression match and push to array

    Hi all,

    Been trying to tackle this problem I have for a while now and I'm sure it's simple but I just can't get it to work.

    Basically I have a file containing some string content:

    e.g.

    Name: php
    Version: 5.1.6
    Description: PHP is an HTML-embedded scripting language. PHP attempts to
    make it easy for developers to write dynamically generated webpages.

    I'd like to use divide the file up based on Name, Version & Description and push each string into a associative array

    i.e.

    [name] => 'php'
    [version] => '5.1.6'
    [description] => 'PHP is an HTML-embedded scripting language. PHP attempts to make it easy for developers to write dynamically generated webpages.'

    I'm currently experimenting with preg_match_all to do this which seems to work but only for values which are no longer and a single line. Any value more than one line like Description gets stripped and only the last line sets stored in the array.

    Does anyone out there know if I'm doing this correct or is there a better method.

    Thanks for your time

    Regards

    Mark

  2. #2
    SitePoint Guru aamonkey's Avatar
    Join Date
    Sep 2004
    Location
    kansas
    Posts
    953
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    with preg_match_all you will want to look at the 's' modifier, or it might be easier with preg_split:
    Code PHP:
    $str = 'Name: php
    Version: 5.1.6
    Description: PHP is an HTML-embedded scripting language. PHP attempts to
    make it easy for developers to write dynamically generated webpages.';
     
    $matches = preg_split('#(^|\n)(Name|Version|Description):#', $str, -1, PREG_SPLIT_NO_EMPTY);
     
    echo '<pre>';
    print_r($matches);
    echo '</pre>';
    aaron-fisher.com - PHP articles and more

  3. #3
    SitePoint Member
    Join Date
    Nov 2010
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Smile

    That's fantasic.

    Thank you!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •