2012-05-08 140 views
2

我通常都很高效地解決PHP問題,但是由於這個特定的問題,我似乎無法找到工作解決方案。替換字符串中括號中任何括號的所有出現

我有一個由標準文本組成的字符串,在文本中會有一些關鍵字被[方括號]包圍,我想將它轉換爲鏈接,但它不是一個簡單的比較字符串的情況預定義的「已知」關鍵字數組並進行簡單的替換,因爲[方括號]的內容可以是任何內容。

比如我就如下:

John Roberts is a jazz musician from Florida born in 1934. Some of his notable works include [A Gray Sky] and [Sophomore Effort]. 

應該變成如下:

John Roberts is a jazz musician from Florida born in 1934. Some of his notable works include <a href="search.php?search=a+gray+sky">A Gray Sky</a> and <a href="search.php?search=sophomore+effort">Sophomore Effort</a>. 

應當注意的是:

  • 的$字符串將包含未知數量的[方括號詞]。
  • 使用方括號不是必需的,如果它會導致問題,但現在看來我最方便的方法。

我並不是要求別人給我代碼,我需要的是有人告訴我應該調查什麼樣的PHP函數,並指向正確的方向!

非常感謝大家,謝謝Stackoverflow讓我有機會問!

+0

的preg_match \替換爲[],然後進行urlencode() – 2012-05-08 02:58:33

回答

3
$string = "John Roberts is a jazz musician from Florida born in 1934. Some of his notable works include [A Gray Sky] and [Sophomore Effort]."; 

function rep_callback($match) 
{ 
     $query = substr($match[0],1,-1); 
     $query = urlencode($query); 
     $link = '<a href="search.php?search='.$query.'">'.$match[0].'</a>'; 
     return $link; 
} 

echo $string."\n"; 
echo preg_replace_callback("/\[.+\]/U", "rep_callback", $string)."\n"; 

輸出:

John Roberts is a jazz musician from Florida born in 1934. Some of his notable works include [A Gray Sky] and [Sophomore Effort]. 
John Roberts is a jazz musician from Florida born in 1934. Some of his notable works include <a href="search.php?search=A+Gray+Sky">[A Gray Sky]</a> and <a href="search.php?search=Sophomore+Effort">[Sophomore Effort]</a>. 
+0

我猜你沒有讀的問題這一點「我不要求別人給我代碼「:-) – 2012-05-08 03:08:31

+1

事實上,我沒有,但即使我做了 - 我覺得喜歡它:) – ccKep

+0

@ccKep ...聖牛!編碼者之間的上帝! googleplex無法描述你剛剛救了多少個小時:D – juanitojuandejuanes

相關問題