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.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度