php preg_replace 模式 - 替换逗号之间的文本

php preg_replace pattern - replace text between commas

我有一个数组中的一串单词,我正在使用 preg_replace 将每个单词组成一个 link。目前我的代码有效,每个单词都被转换成 link.

这是我的代码:

$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 个单词作为一个单词时 link。比如我有一个关键字"blue curtains"。该脚本将分别为单词 "blue" 和 "curtains" 创建一个 link。我用逗号分隔关键字,我希望 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>

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);

OR

$newkeys = preg_replace("/(?!(?:[^<]+>|[^>]+<\/a>))\b([a-z' ']+)\b/is",    sprintf($template, "\1"), $keywords);

echo $newkeys;

输出:- http://prntscr.com/77tkyb

注意:- 我刚刚在你的 preg_replace 中添加了一个白色-space。你可以很容易地到达它所在的位置。希望我说清楚了。

preg_replace 中缺少匹配的 white-space 和单词,我只添加了。