preg_replace How to search 2 lines ?

Discussion in 'PHP' started by pixmania, Sep 7, 2009.

  1. #1
    Hello

    I'm having a hard time understanding preg_replace or perhaps I should be using a different method, however heres my problem.

    For example, on a page I might have the following code spread over 2 lines

    pic_height = 15;
    pic_width = 15;

    So I'm putting these two lines of text in my preg_replace code as below but its not working, ie: its not looking at the two lines. if it was one string pic_height = 15; that would work fine, but it would change every string that matches, which wont work for me, as it must be an exact match of the two lines or it could screw up images and sizes on a page.

    $final = preg_replace('#pic_height = 15;pic_width = 15;#','pic_height = 20;pic_width = 20;',$final);

    I've been trying \r \n and things like that, but I just cant figure it out.

    ...any care to tell me where I'm going wrong ?
     
    pixmania, Sep 7, 2009 IP
  2. premiumscripts

    premiumscripts Peon

    Messages:
    1,062
    Likes Received:
    48
    Best Answers:
    0
    Trophy Points:
    0
    #2
    $final = preg_replace('#pic_height = 15;.*?pic_width = 15;#m','pic_height = 20;pic_width = 20;',$final);
     
    premiumscripts, Sep 7, 2009 IP
  3. pixmania

    pixmania Peon

    Messages:
    229
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks @premiumscripts

    It doesn't seem to work...

    (.*?) or your .*? would represent any characters in between, does it include spaces ?

    .. and the m at the end represents multi-part search?
     
    pixmania, Sep 7, 2009 IP
  4. premiumscripts

    premiumscripts Peon

    Messages:
    1,062
    Likes Received:
    48
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Actually the modifier should be sm instead of just m:

    $final = preg_replace('/pic_height = 15;(.*?)pic_width = 15;/sm','pic_height = 20;$1pic_width = 20;',$final);
    
    PHP:
    Read about modifiers here: http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php

    Edit: added $1 so that section doesn't get lost. The (.*?)
     
    premiumscripts, Sep 7, 2009 IP