【发布时间】:2015-05-21 18:36:25
【问题描述】:
我在一个数组中有一个单词字符串,我正在使用preg_replace 将每个单词变成一个链接。目前我的代码有效,每个单词都被转换成一个链接。
这是我的代码:
$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);
现在,唯一的问题是当我希望 2 或 3 个单词成为单个链接时。例如,我有一个关键字“蓝色窗帘”。该脚本将分别为“blue”和“curtains”这个词创建一个链接。我有用逗号分隔的关键字,我希望 preg_replace 只替换逗号之间的文本。
我已经尝试过使用该模式,但我无法弄清楚该模式会是什么。
澄清一下,目前的输出如下:
<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>
虽然我想实现以下输出:
<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>
【问题讨论】:
-
请将您的预期输出也放入您的代码中
-
您好,感谢您的快速回复。我刚刚编辑了我的问题,添加了当前和预期的输出
-
请检查我的答案。
标签: php preg-replace