PDA

View Full Version : amazon link regex help


the_sisko
08-13-2004, 02:49 PM
Hi guys,

I'm trying to replace a normal amazon.de Link oder any amazon.de Link with a affiliate ID to my own:

http://www.amazon.de/exec/obidos/ASIN/B0001RTYDG/ref=amb_center-4_113630_1/028-9904298-7328563

-->

http://www.amazon.de/exec/obidos/ASIN/B0001RTYDG/chemieonline

I wrote a function for it but have some probs. There must be a whitespace at the endling of the string. otherwise if the url is the last thing in the string it won't work... I added an extra whitespace at the end in the funktion.
Also if the link ends like http://www.amazon.de/exec/obidos/ASIN/B0001RTYDG/ref=amb_center-4_113630_1/028-9904298-7328563[ /url ] the [ /url ] get cut of...

Need a little help as I'm not that regex guy:
<?
//replace function
function cdk_a($string,$id="chemieonline") {
$string .= " ";
return preg_replace("/(http:\/\/|http:\/\/www.|www.|)amazon.de\/exec\/obidos\/ASIN\/([A-Z0-9]+)([^\"\n]*?)\s+/i","http://www.amazon.de/exec/obidos/ASIN/$2/$id ",$string);
}

//test urls
$url ="Schreiben wir einen kleinen Text mit einer Url zu Amazon mit allen Werten:
http://www.amazon.de/exec/obidos/ASIN/B0001RTYDG/ref=amb_center-4_113630_1/028-9904298-7328563 ,
dann lassen wir das www weg: http://amazon.de/exec/obidos/ASIN/B0001RTYDG/ref=amb_center-4_113630_1/028-9904298-7328563 ,
oder auch einfach das http: www.amazon.de/exec/obidos/ASIN/B0001RTYDG/ref=amb_center-4_113630_1/028-9904298-7328563 ,
und zum Schlu? einfach beides: amazon.de/exec/obidos/ASIN/B0001RTYDG/ref=amb_center-4_113630_1/028-9904298-7328563";

//do replace
$ausgabe = cdk_a($url);


//ausgabe
echo "<blockquote>";
print($url);
echo "</blockquote>\n";
echo "<blockquote>";
print($ausgabe);
echo "</blockquote>";


?>

Modin
08-13-2004, 05:14 PM
When using backtracking, you want the $2 to be passed to regex engine. Though, normally php will evaluate it.

So, to ensure it's passed as a dollar sign and not as an evaluated variable you need to add a slash before it. Like so...

preg_replace("/(http:\/\/|http:\/\/www.|www.|)amazon.de\/exec\/obidos\/ASIN\/([A-Z0-9]+)([^\"\n]*?)\s+/i","http://www.amazon.de/exec/obidos/ASIN/\$2/$id ",$string);


Hope this helps,
Modin