Can't get preg_match_all to work properly

Discussion in 'PHP' started by patter, Jul 6, 2011.

  1. #1
    I'm trying to create a function that will search a string for special characters and replace them but I can't get preg_match_all to break the string apart correctly.
    Below is code showing the problem. I surround the text to be replaced with %%+ and %%-.
    
    [PHP]$str = "first entry is %%+FIRST%%- and the second entry is %%+SECOND%%-";
    
    preg_match_all("/%%\+(.*)%%-/", $str, $matches );
    
    OUTPUT IS
    
     Array
    (
        [0] => Array
            (
                [0] => %%+FIRST%%- and the second entry is %%+SECOND%%-
            )
    
        [1] => Array
            (
                [0] => FIRST%%- and the second entry is %%+SECOND
            )
    )
    
    PHP:
    What I'm looking for in the output is something like this
     Array
    (
        [0] => Array
            (
                [0] => %%+FIRST%%- and the second entry is %%+SECOND%%-
            )
    
        [1] => Array
            (
                [0] => FIRST
            )
    )
    PHP:
    I would appreciate it if anyone can point out my mistake or provide a better way of doing this.
     
    patter, Jul 6, 2011 IP
  2. Kyosys

    Kyosys Peon

    Messages:
    226
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    0
    #2
    try (.*?) instead of (.*)

    basically
    (.*) is greedy and (.*?) will stop at the first occurance
     
    Kyosys, Jul 6, 2011 IP
  3. patter

    patter Member

    Messages:
    32
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #3
    That worked perfectly. Thank you for the solution. :)
     
    patter, Jul 6, 2011 IP