Regular Expression Help (preg_match)

Discussion in 'PHP' started by DesignWeb, Sep 3, 2010.

  1. #1
    Hi,

    I have this example string

    
    <tag> some random string here </tag>
    <tag> some random this is what we want more random </tag>
    <tag> another random string here </tag>
    
    Code (markup):
    This code works:
    
    <?php 
    if(preg_match('/<tag>(.*this is what we want.*)<\/tag>/si', $string) {
    echo 'Ok';
    }
    ?>
    PHP:
    But it works also if we have the following string:
    
    <tag> some random string here </tag>
    some random this is what we want more random
    <tag> another random string here </tag>
    
    Code (markup):
    I don't want the regexp to work for the above string because it doesn't wrapped with <tag> and </tag>

    Any ideas how should I use the regexp?
     
    DesignWeb, Sep 3, 2010 IP
  2. lukeg32

    lukeg32 Peon

    Messages:
    645
    Likes Received:
    19
    Best Answers:
    1
    Trophy Points:
    0
    #2
    This will work;

    <?php
    $str = "<tag> some random string here </tag>
    some random this is what we want more random
    <tag> another random string here </tag>";
    
    preg_match_all('/<tag>(.*?)<\/tag>/si', $str, $ff);
    print_r($ff);
    ?>
    
    PHP:
    OUTPUT:
    Array
    (
        [0] => Array
            (
                [0] => <tag> some random string here </tag>
                [1] => <tag> another random string here </tag>
            )
    
        [1] => Array
            (
                [0] =>  some random string here 
                [1] =>  another random string here 
            )
    
    )
    
    Code (markup):
     
    lukeg32, Sep 3, 2010 IP
  3. DesignWeb

    DesignWeb Active Member

    Messages:
    251
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    58
    #3
    @lukeg32 thanks, but I want to find "this is what we want" and it should be wrapped with <tag> and </tag>.
    The phrase "this is what we want" should be used in the regexp because it is important
     
    DesignWeb, Sep 3, 2010 IP
  4. danx10

    danx10 Peon

    Messages:
    1,179
    Likes Received:
    44
    Best Answers:
    2
    Trophy Points:
    0
    #4
    preg_match('#<tag>(.*?this is what we want.*?)</tag>#si', $string);
    PHP:
     
    danx10, Sep 3, 2010 IP
  5. tunnbooy

    tunnbooy Greenhorn

    Messages:
    21
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    11
    #5
    can u suggest me another function batter then preg_match. b/c i always gets error while using this funtion
     
    tunnbooy, Sep 3, 2010 IP
  6. exam

    exam Peon

    Messages:
    2,434
    Likes Received:
    120
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Use preg_split to split the text into lines, then remove the unwanted tags from each item in a loop.
     
    exam, Sep 3, 2010 IP