douyi7055 2015-05-21 18:36
浏览 30
已采纳

php preg_replace pattern - 用逗号替换文本

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>
  • 写回答

1条回答 默认 最新

  • douguan3470 2015-05-21 19:01
    关注

    A little bit change in preg_replace code and your job will done :-

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

    Output:- http://prntscr.com/77tkyb

    Note:- I just added an white-space in your preg_replace. And you can easily get where it is. I hope i am clear.

    Matching white-space along with words is missing there in preg_replace and i added that only.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集