It is Possible to use a function to format the output of a preg_replace. This can be accomplished using backreferences.
the following example assumes that freelance-window.com sells books and pays commissions to affilates who send customers to them.
PHP Code:
//original link or links nested in other content
$aff = "< a href=\"http://www.freelance-window.com/books.php?bookid=5&\">php book</a>";
//this function will add the id to every match found
function parseid($id){
$template = "http://www.yoursite.com/books.php?bookid={id}&referid=yourname";
return str_replace("{id}",$id,$template);
}
//match all the book urls on the site
$urlpattern = "/http:\/\/[^=]+([^&]+)/";
//store value of id
$backreferenceid = "$1";
//parse urls matching pattern using template
$parse_aff = preg_replace($urlpattern,parseid($backreferenceid),$aff);
echo($parse_aff);
If i did everything right the above code should output:
Code:
http://www.yoursite.com/books.php?bookid=5&referid=yourname
it seems trivial at first but its very useful when taking information
off other websites, parsing that information and redisplaying it on
your own. You may also parse info for the purpose of storing it in the
database.
The whole point of this is
1) make the script neater
2) function parseid allows for much more complex operations using the
information found in a match. this function could also be part of a
class...example
PHP Code:
class scraper{
function parseid($id){}
}
$freelance_window= new scraper;
$freelance_window->parseid($backreferenceid);