0

I have the following short code I want to use to automatically generate Amazon Affiliate links in my posts [amazon region=com asin=xxxxxx].

How can I get the 'region' a and 'asin' from this string and convert every occurrence of it into my php function getAffiliateLink("com","xxxxxxxx")?

I can have multiple of these strings with different numbers on the page.

I have been looking into preg_replace and regex but I can't figure out how to do this for this particular example.

7
  • elaborate your expected result: should it be literally getAffiliateLink($region,$asin) or getAffiliateLink('com','xxxxxx') ? Commented Jan 22, 2018 at 22:08
  • When for example I put [amazon region=com asin=1234567] then I want this to be replaced in my code with getAffiliateLink("com","1234567"). There can be more links like these in one post with different asin numbers. ( I edited my question to make it more clear) Commented Jan 22, 2018 at 22:10
  • You may want to show us your efforts on it. Commented Jan 22, 2018 at 22:16
  • @revo I am completely new to preg_replace. I have looked into regex and regular expressions, but I have no idea how to implement that for this case. Commented Jan 22, 2018 at 22:17
  • Are region and asin always in the same order? or it can be different? Commented Jan 22, 2018 at 22:35

1 Answer 1

1

Ok so I found the solution. Because I want to replace the string with a function, I had to use preg_replace_callback().

This is my working solution:

$content = preg_replace_callback('/\[amazon region=([^\b]+) asin=([^\b]+)\]/', 'callback', $content);

function callback ($matches) {
    print_r($matches);
    return getAffiliateLink("$matches[1]","$matches[2]");
}

echo $content;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.