View Full Version : Problem while using regular expression

01-24-2007, 12:08 PM

I have facing a problem. Kindly help

I have a Regular expression

$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

$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

<img src = "abc/first_pic.jpg">

<img src = "admin/img/picture.jpg>"

My Requirement is to change the path "abc/first_pic.jpg" to "images/first.jpg"
"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

01-24-2007, 04:00 PM
I don't like giving out full code, but what about this:

$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:


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