Forum Moderators: coopster

Message Too Old, No Replies

replacing images with regex.

         

tekomp

11:20 pm on Mar 11, 2006 (gmt 0)

10+ Year Member



Hi,

I'm trying to replace all images that are found within a string with a different image location. I can find the images and store those in an array, but not sure how to replace those with a modifed value. Here's what I have so far:

[code]
preg_match_all("¦src\=\"?'?`?([[:alnum:]:?=&@/._+-]+)\"?'?`?¦i", $string, $matches);
[code]

This puts the strings that I need to replace into $matches[1].

I need to take those strings, modify them, and then replace the original string with the new image links. Any ideas?

Thanks.

zRonin

2:05 am on Mar 12, 2006 (gmt 0)

10+ Year Member



Use preg_replace_callback:
mixed preg_replace_callback ( mixed pattern, callback callback, mixed subject [, int limit [, int &count]] )

Coppied from php.net:

The behavior of this function is almost identical to preg_replace(), except for the fact that instead of replacement parameter, one should specify a callback that will be called and passed an array of matched elements in the subject string. The callback should return the replacement string.

<?php
// this text was used in 2002
// we want to get this up to date for 2003
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
// the callback function
function next_year($matches)
{
// as usual: $matches[0] is the complete match
// $matches[1] the match for the first subpattern
// enclosed in '(...)' and so on
return $matches[1].($matches[2]+1);
}
echo preg_replace_callback(
"¦(\d{2}/\d{2}/)(\d{4})¦",
"next_year",
$text);
// result is:
// April fools day is 04/01/2003
// Last christmas was 12/24/2002
?>

If you dont need to use a callback you can just use the regular search and replace:
mixed preg_replace ( mixed pattern, mixed replacement, mixed subject [, int limit [, int &count]] )

tekomp

4:06 am on Mar 12, 2006 (gmt 0)

10+ Year Member



Thanks, that works great.

Now I'm trying to match just the image name from the first regex match which is the entire src of the image. I'm trying to use the following to match against http://www.example.com/images/asdf.jpg

preg_match("/\/.+?\.jpg/", $matches[1], $imagematch);

I'm trying to just return asdf.jpg

Thanks.

coopster

1:30 pm on Mar 12, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You could just grab the basename [php.net] of that string now.