Probably Simple Regex Problem (but I still don't get it)

Discussion in 'Programming' started by Kellerkind, Jun 10, 2008.

  1. #1
    Ok I want to replace the height and width tag of an image.

    It comes in this form within the img tag:

    height="300" width="300"
    Code (markup):
    This here is the code that works to replace it with something else but I can't get it working with just one preg_replace.
    
    function img_modify($text) {
    		$pattern = '(\bheight\b[\=\s][\".]*[a-zA-Z0-9\-]*"\s)';
    		$text = preg_replace($pattern, 'height="200"', $text);
    		$pattern = '(\bwidth\b[\=\s][\".]*[a-zA-Z0-9\-]*"\s)';
    		$text = preg_replace($pattern, 'width="200"', $text);
            return $text;
        }
    
    Code (markup):
    Would be great if anyone could enlighten me!
     
    Kellerkind, Jun 10, 2008 IP
  2. rohan_shenoy

    rohan_shenoy Active Member

    Messages:
    441
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    60
    #2
    
    <?php
    $img="<img src=\"images/pic.png\" width=\"300\" height=\"200px\" alt=\"My pic\">";
    $pattern[0]="/width=\"[a-zA-Z0-9]+\"/i";
    $pattern[1]="/height=\"[a-zA-Z0-9]+\"/i";
    $replacement[0]="width=\"NEW-WIDTH\"";//set your new width
    $replacement[1]="height=\"NEW-HEIGHT\"";//set your new height
    $img=preg_replace($pattern,$replacement,$img);
    //$img is the new image markup: Eg: <img src="images/pic.png" width="NEW-WIDTH" height="NEW-HEIGHT" alt="My pic">
    ?>
    
    PHP:
    Enjoy :)
     
    rohan_shenoy, Jun 10, 2008 IP
  3. Kellerkind

    Kellerkind Active Member

    Messages:
    160
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #3
    Rohan you rock thanks!
     
    Kellerkind, Jun 10, 2008 IP
  4. rohan_shenoy

    rohan_shenoy Active Member

    Messages:
    441
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    60
    #4
    Welcome :)
     
    rohan_shenoy, Jun 11, 2008 IP