SitePoint Sponsor

User Tag List

Results 1 to 5 of 5

Thread: Grep

  1. #1
    SitePoint Addict
    Join Date
    Jun 2008
    Posts
    205
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Grep

    Hi,

    I have a file contents in a file.

    $data=file('myfile.txt');

    From this I have to grep for the strings between "Results" and "seconds".

  2. #2
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Use file_get_contents to load the file into a string. Then use preg_match to search in it, using perl regex syntax.

  3. #3
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Here you go.
    PHP Code:
    <?php
    foreach(file('somefile.txt') as $sLine)
    {
        echo (
    === preg_match('~(?<=Results)(.+?)(?=seconds)~'$sLine$aMatch)) ? $aMatch[0] : '' ;
    }
    ?>
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  4. #4
    SitePoint Addict
    Join Date
    Jun 2008
    Posts
    205
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi,

    Thanks for the reply.

    Can you please tell me how to select only last value i.e 72 from this string
    <b>1</b> - <b>10</b> of about <b>72</b>

  5. #5
    @php.net Salathe's Avatar
    Join Date
    Dec 2004
    Location
    Edinburgh
    Posts
    1,397
    Mentioned
    63 Post(s)
    Tagged
    0 Thread(s)
    You could use a regular expression to look for a <b> encapsulated number. Here's an example which takes comma-separated thousands into effect and gives an integer result.

    PHP Code:
    $string '<b>1</b> - <b>10</b> of about <b>72</b>';
    $total  0;
    if (
    preg_match('#<b>([\d,]+)</b>$#'$string$match))
    {
        
    $total = (int) str_replace(','''$match[1]);
    }

    echo 
    'There were about '$total' matches.'
    Salathe
    Software Developer and PHP Manual Author.


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
  •