Regular Expressions help needed

Discussion in 'PHP' started by Marko, Jan 20, 2008.

  1. #1
    Hi I am creating fetch class and I got a problem with regexp in php.

    For example this is a text:

    <b>details</b>
    </a>
    </td>
    </tr></table>
    </div>

    <p class="desc">
    Some text here…
    <i>
    Written by Admin
    </i>
    </p>

    Some text again

    And I want to grab everything between <p class="desc"> and Written by.
    So result in this case should be: Some text here…
    <i>

    How to this with PHP?
     
    Marko, Jan 20, 2008 IP
  2. jayshah

    jayshah Peon

    Messages:
    1,126
    Likes Received:
    68
    Best Answers:
    1
    Trophy Points:
    0
    #2
    Hi,

    You can use a simple explode() sequence if you like:

    This code will run as it is:

    
    <?php
    
    // This is our HTML
    
    $html = <<<html
    
    <b>details</b>
    </a>
    </td>
    </tr></table>
    </div>
    
    <p class="desc">
    Some text here.
    <i>
    Written by Admin
    </i>
    </p>
    html;
    
    $get = explode('<p class="desc">', $html);
    $get = explode('Written by', $get[1]);
    // Remove any whitespace / newlines
    $get = trim($get[0]);
    
    echo $get;
    ?>
    
    PHP:
    Jay
     
    jayshah, Jan 20, 2008 IP
  3. Kaizoku

    Kaizoku Well-Known Member

    Messages:
    1,261
    Likes Received:
    20
    Best Answers:
    1
    Trophy Points:
    105
    #3
    Use the "s" modifier to make dot metacharacter in the pattern matches all characters, including newlines.

    Debug
    
    preg_match("/<p.*>(.*)Written by/s", $input, $output);
    print_r($output);
    
    PHP:
    Real
    
    preg_match("/<p.*>(.*)Written by/s", $input, $output);
    echo $output[1];
    
    PHP:
     
    Kaizoku, Jan 20, 2008 IP
  4. SmallPotatoes

    SmallPotatoes Peon

    Messages:
    1,321
    Likes Received:
    41
    Best Answers:
    0
    Trophy Points:
    0
    #4
    I think you want to change <p.*> to <p.*?> - otherwise the * will be greedy. If there are any tags in the paragraph (e.g., <i>) then it will grab everything up until the last of them.
     
    SmallPotatoes, Jan 20, 2008 IP
  5. Marko

    Marko Peon

    Messages:
    248
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Tnx a lot problem solved
     
    Marko, Jan 20, 2008 IP