php
  • preg-replace
  • 2015-05-21 221 views 0 likes 
    0

    我有一個數組中的單詞串,我使用preg_replace使每個單詞成爲一個鏈接。目前我的代碼有效,每個單詞都被轉換成一個鏈接。PHP 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個字是一個單一的鏈接。例如,我有一個關鍵字「藍色窗簾」。該腳本將分別爲單詞「藍色」和「窗簾」創建鏈接。我有以逗號分隔的關鍵字,並且我希望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> 
    
    +1

    把你的預期輸出還在你的代碼請致電 –

    +0

    嗨,謝謝你的快速回復。我剛剛編輯我的問題添加了當前和預期的輸出 – Adam

    +0

    請檢查我的答案。 –

    回答

    0

    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中丟失,我補充說只有。

    +0

    這完全符合我的要求 - 謝謝! – Adam

    +0

    因此,將其標記爲您的答案,以便其他人可以從這篇文章中獲益。謝謝:))) –

    +0

    是的,只是 - 再次感謝:) – Adam

    相關問題