【问题标题】:php preg_replace pattern - replace text between commasphp preg_replace 模式 - 替换逗号之间的文本
【发布时间】: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


【解决方案1】:

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 中添加了一个空格。你可以很容易地找到它的位置。我希望我很清楚。

preg_replace 中缺少匹配的空格和单词,我仅添加了这一点。

【讨论】:

  • 因此将其标记为您的答案,以便其他人可以从这篇文章中受益。谢谢:)))
猜你喜欢
  • 2020-02-20
  • 1970-01-01
  • 1970-01-01
  • 2018-05-14
  • 2016-07-21
  • 2014-10-31
  • 2015-05-08
  • 2012-03-08
  • 2021-03-24
相关资源
最近更新 更多