Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Apr 2005
    Location
    Lahore, Pakistan
    Posts
    150
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Problem while using regular expression

    Hello,

    I have facing a problem. Kindly help

    I have a Regular expression

    PHP Code:

    $pattern 
    '!<img src="([^"]+)"!'
    I have a php code which reads a html file, then that regular expression searches <img> tag
    Becoz according to my requirement i have to change the default path found in <img> tag.

    Here is another regular expression

    PHP Code:

    $replace 
    '<img src=images/'."$1"
    This is used to replace the current path found in an html document.


    Suppose, i have an html file, in that html file there are two <img> tags and those have these paths like

    Code:
    <img src = "abc/first_pic.jpg">
    Code:
    <img src = "admin/img/picture.jpg>"
    My Requirement is to change the path "abc/first_pic.jpg" to "images/first.jpg"
    and
    "admin/img/picture.jpg" to "images/picture.jpg"

    Means in every requirement i use this path i.e. 'images/anypicturefile.jpg'

    For that purpose i must change my current regular expression which is
    $replace = '<img src=images/'."$1";

    Can anybody help me to change this regular expression $replace = '<img src=images/'."$1"; ,so that it fullfills the above requirement

  • #2
    Senior Coder
    Join Date
    Jan 2007
    Posts
    1,648
    Thanks
    1
    Thanked 58 Times in 54 Posts
    I don't like giving out full code, but what about this:

    PHP Code:
    $html '
    <img src="abc/img.jpg" />
    <img src="sdf/abc/img.jpg" />
    '
    ;
    function 
    tmpCallback($matches) {
        
    // the filename is the first match (0 is the whole match)
        
    $str $matches[1];
        
    // find the last / and return everything past that (string starts at 0)
        
    $file substr(strrchr($str'/'), 1);
        
    // return the new format
        
    return '<img src="images/' $file '"';
    }
    $html preg_replace_callback('!<img src="([^"]+?)"!'$html'tmpCallback'); 
    More information on preg_replace_callback:

    http://us3.php.net/manual/en/functio...e-callback.php

    Remember that the IMG tag may contain characters before and/or after the src attribute so filter for that in your regular expression.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •