我有一個數組中的單詞串,我使用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>
把你的預期輸出還在你的代碼請致電 –
嗨,謝謝你的快速回復。我剛剛編輯我的問題添加了當前和預期的輸出 – Adam
請檢查我的答案。 –