regular expressions conditional patterns

Discussion in 'PHP' started by french-webbie, May 14, 2008.

  1. #1
    Hi,
    I want to replace in a string all instances of width="xxx" by width="400" but only if xxx > 400.
    My first approach with no condition is using:
    preg_replace('/width="(\d+?)"/i', 'width="400"', $string);

    Is it possible to use a conditional pattern in that case? And how?
     
    french-webbie, May 14, 2008 IP
  2. pozzad

    pozzad Member

    Messages:
    7
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    36
    #2
    In my opinion it isn't possible.
     
    pozzad, May 14, 2008 IP
  3. Barti1987

    Barti1987 Well-Known Member

    Messages:
    2,703
    Likes Received:
    115
    Best Answers:
    0
    Trophy Points:
    185
    #3
    
    preg_replace('/width="(4[0-9]+[0-9]+)"/i', 'width="400"', $string);
    
    PHP:
    Replace every thing starting with 4XX should do it.

    Peace,
     
    Barti1987, May 14, 2008 IP
  4. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #4
    #width="[4-9]\d{2,}"#i
    Code (markup):
     
    joebert, May 14, 2008 IP
  5. french-webbie

    french-webbie Peon

    Messages:
    194
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Is it possible to use a regular expression with a conditional pattern to replace any number greater than 400 in the second term of the preg_replace?
    I tried this:
    preg_replace('/width="(.*?)"/i', '/(?(\\1 > 400) width="400")/', $string);
    but it did not work.
    Any idea?
     
    french-webbie, May 14, 2008 IP
  6. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #6
    You're making it alot more complicated than it needs to be.

    Check out preg_replace_callback, you can specify a function to handle replacement with it.
     
    joebert, May 14, 2008 IP
  7. french-webbie

    french-webbie Peon

    Messages:
    194
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #7
    Thanks a lot, Joebert !

    Here is the final working code, if anyone is interested:

    function limitWidth($matches) {
    if ($matches[1] > 400) return 'width="400"';
    return $matches[0];
    }
    $string = preg_replace_callback('/width="(\d+?)"/i', 'limitWidth', string);
     
    french-webbie, May 14, 2008 IP