Welcome to WebmasterWorld Guest from 100.26.176.182

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

replacing images with regex.

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

New User

10+ Year Member

joined:Apr 6, 2005
posts:36
votes: 0


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.

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

Junior Member

10+ Year Member

joined:June 7, 2005
posts:53
votes: 0


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]] )

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

New User

10+ Year Member

joined:Apr 6, 2005
posts:36
votes: 0


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.

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

Administrator

WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:July 31, 2003
posts:12555
votes: 3


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

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members