I have a string of words in an array, and I am using preg_replace
to make each word into a link. Currently my code works, and each word is transformed into a link.
Here is my code:
$keywords = "shoes,hats,blue curtains,red curtains,tables,kitchen tables";
$template = '<a href="http://domain.com/%1$s">%1$s</a>';
$newkeys = preg_replace("/(?!(?:[^<]+>|[^>]+<\/a>))\b([a-z]+)\b/is", sprintf($template, "\\1"), $keywords);
Now, the only problem is that when I want 2 or 3 words to be a single link. For example, I have a keyword "blue curtains". The script would create a link for the word "blue" and "curtains" separately. I have the keywords separated by commas, and I would like the preg_replace
to only replace the text between the commas.
I've tried playing around with the pattern, but I just can't figure out what the pattern would be.
Just to clarify, currently the output looks as follows:
<a href="http://domain.com/shoes">shoes</a>,<a href="http://domain.com/hats">hats</a>,<a href="http://domain.com/blue">blue</a> <a href="http://domain.com/curtains">curtains</a>,<a href="http://domain.com/red">red</a> <a href="http://domain.com/curtains">curtains</a>,<a href="http://domain.com/tables">tables</a>,<a href="http://domain.com/kitchen">kitchen</a> <a href="http://domain.com/tables">tables</a>
While I want to achieve the following output:
<a href="http://domain.com/shoes">shoes</a>,<a href="http://domain.com/hats">hats</a>,<a href="http://domain.com/blue curtains">blue curtains</a>,<a href="http://domain.com/red curtains">red curtains</a>,<a href="http://domain.com/tables">tables</a>,<a href="http://domain.com/kitchen tables">kitchen tables</a>