Forum Moderators: coopster

Message Too Old, No Replies

Regex help needed

including amazon id with links

         

mirthe_v

2:30 pm on Jun 2, 2003 (gmt 0)

10+ Year Member



Hi,

I have a webblog, which is simple text. However, I include a lot of links to Amazon products, for more information on stuff I mention.

I would like to use some sort of RegEx with my PHP to change Amazon links to include my Amazon Associate id.

So:

$mytext = '<p>This is <A HREF="http://www.amazon.com/exec/obidos/ASIN/0679781587">link</A> bla bla bla bla bla bla bla.<br>This is a <a href="http://www.google.com">normal link</a>, and should not be changed. And here is another, bla bla bla bla bla bla bla<a href="http://www.amazon.com/exec/obidos/ASIN/0316763721">2nd link</a>. Bla bla bla bla.</p>';

would thus become:

$mytext = '<p>This is <A HREF="http://www.amazon.com/exec/obidos/ASIN/0679781587/MY-AMAZON-ID">link</A> bla bla bla bla bla bla bla.<br>This is a <a href="http://www.google.com">normal link</a>, and should not be changed. And here is another, bla bla bla bla bla bla bla<a href="http://www.amazon.com/exec/obidos/ASIN/0316763721/MY-AMAZON-ID">2nd link</a>. Bla bla bla bla.</p>';

However, I have tried a number of things, but am not able to get this done. Hope someone out there can help.

Cheers!

Regards
Mirthe

bcolflesh

3:46 pm on Jun 2, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



How about:

$mytextReplaced = str_replace("$mytext", "">", "/MY-AMAZON-ID"">")

us2.php.net/manual/en/function.str-replace.php

Regards,
Brent

mirthe_v

6:50 am on Jun 3, 2003 (gmt 0)

10+ Year Member



Hi, thanks for reacting so quickly.

Though your code would work, it would replace ALL links, instead of only the Amazon links.

-Mirthe

strimmerboy

7:12 am on Jun 3, 2003 (gmt 0)

10+ Year Member



If you can rely on the trailing number being a certain length (10 digits in this case), how about:

$str = '<a href="whatever/1234567890">link<a> <a href="yada">leave this alone</a><br>';
$str2 = '<a href="whatever/1234567890/">other link</a> <a href="yada">leave this alone</a>';
print ereg_replace('([0-9]{10})/?"', '\\1/myid/"', $str);
print ereg_replace('([0-9]{10})/?"', '\\1/myid/"', $str2);

the /? should catch optional trailing slashes

mirthe_v

2:31 pm on Jun 11, 2003 (gmt 0)

10+ Year Member



I think that should work!
I'll have to try it out later on, when I'm back home.
Thanks for now...